所以,我一直在努力让 ajax 工作。 这是我之前的问题:AJAX (admin_url('admin-ajax.php');?action=) Not Found
无论如何,我决定缩小范围,只保留必要的文件。
这是设置。
test.php
<div class="test">
<a href="#test_demo" id="demo">Items</a>
</div>
<div id="test_demo"> </div>
<script>
jQuery(document).ready(function() {
jQuery('.test a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: 'html',
data: ({ action: 'test_tab', id: tab_id}),
success: function(data){
jQuery('#test_' + tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
函数.php
function test_tab_callback() {
$template_part_path = 'page-parts/test_' . $_GET['id'];
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_test_tab', 'test_tab_callback');
add_action('wp_ajax_nopriv_test_tab', 'test_tab_callback');
test_demo.php
<div id="test_demo_content">Demo Content</div>
这是我对它应该如何工作的想法。
- test.php:当用户点击
Items
按钮时,jQuery 中的tab_id
变量保存 anchorid
(在本例中,它将是id="demo"
)。 - 然后调用admin-ajax.php。
- 然后将保存的 ID(“demo”)传递到 function.php 并在变量
$template_part_path = 'page-parts/test_' 中使用。 $_GET['id'];
为test_demo.php
提供 然后调用模板部分,回调给jQuery。
然后将数据“插入”到
jQuery('#test_' + tab_id).html(data);
中,即id="test_demo
.- test_demo.php 的内容应该显示在
#test_demo
div 中。
page-parts/test_demo
但它不起作用。我使用了 console.log(data)
但没有显示任何结果。
我做错了什么?
最佳答案
当您获取“this”的 jquery 对象时,您不能使用引号。这使 tab_id 成为未定义的并破坏了其余部分。
我的意思是:
http://jsfiddle.net/7r1dg7L4/2/
jQuery(document).ready(function() {
jQuery('.test a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
alert(tab_id);
});
});
关于javascript - Ajax 测试(wordpress),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31417742/