【发布时间】:2016-10-07 07:54:29
【问题描述】:
我想将变量传递给特定页面。我找到了一个简单的例子来解释如何在 wordpress 中使用 ajax。
JavaScript:
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
要插入functions.php的PHP片段
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
不幸的是,我无法传递变量。我检查了代码,我得到了这个错误:
Error: ajax_object is not defined
您可能知道获得相同结果的另一种方法吗?
【问题讨论】:
-
wp_localize_script 期望有一个名为 ajax_object 的变量,所以您可以尝试对此发表评论并查看它是否有效,这样您就可以知道错误来自那里吗?
-
嗨,LoicTheAtzec 我不太明白你的例子。我可以请您使用 blockquote 写下您的建议吗?
标签: javascript php jquery ajax wordpress