示例 Wordpress AJAX 调用表示成功,但没有传递应有的数据



这是一个愚蠢的问题,但这里是-

我正试图了解Wordpress的AJAX调用。在我的PHP模块中,我有

function example_ajax_request() {
$fruit = $_POST['fruit'];
echo $fruit;
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

在我的JS文件中,我有

jQuery(document).ready(function ($) {
console.log('ajaxurl', ajaxurl);
// This is the variable we are passing via AJAX
var fruit = 'Banana';
console.log('call fruit', fruit);
// This does the ajax request (The Call).
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action': 'example_ajax_request', // This is our PHP function below
'fruit': 'apple' // This is the variable we are sending via AJAX
},
success: function (data) {
// This outputs the result of the ajax request (The Callback)
window.alert('data', data);
},
error: function (errorThrown) {
window.alert('error', errorThrown);
}
});
});

我不明白的是,当我加载页面时,我会弹出一个带有"data"的弹出窗口,这表示成功功能,但没有实际数据(echo 'someResult';部分(。此外,我在控制台中没有收到任何错误。

@Aliakseyenka Ihar给了我一个想法,我的最终代码是:

<?php function example_ajax_request() {
$fruit = $_REQUEST['fruit'];
echo '{fruit:''.$fruit.''}';
die();
}
// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

以及

jQuery(document).ready(function ($) {
console.log('ajaxurl', ajaxurl);
// This is the variable we are passing via AJAX
var fruit = 'Banana';
console.log('call fruit', fruit);
// This does the ajax request (The Call).
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action': 'example_ajax_request', // This is our PHP function below
'fruit': 'apple' // This is the variable we are sending via AJAX
},
success: function (data) {
// This outputs the result of the ajax request (The Callback)
console.log('the data is: ', data);
},
error: function (errorThrown) {
window.alert('error ' + errorThrown);
}
});
});

问题最终出现在$_POST上,而不是ECHO上。

最新更新