我的 JQuery 代码正在发布,因为成功功能正在触发。问题是 PHP $_POST 请求没有接收到数据。出于调试目的,我尝试使用 alert(data) 来显示我希望的数组,并告诉我是否有办法解析正在传递的内容。相反,警告框只显示“[object Object]”。我需要将这些数据转换为可以在 PHP 中用于回调函数的表单。
这是JQuery:
$(document).ready(function(){
//JQuery for the submission of a new list item.
$('input.[class$="-arrow"]').click(function(e){
e.preventDefault(); //put e in function.
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
if ($(this).hasClass('up-arrow')) {
var arrowdirection = 'up';
var entry = $(this).val();
}
else if ($(this).hasClass('down-arrow')) {
var arrowdirection = 'down';
var entry = $(this).val();
}
var data = {
action: 'cb_lud_arrow_action',
arrow: arrowdirection,
entryID: entry
};
$.ajax ({
type: 'POST',
url: ajaxurl,
data: data,
datatype: "text",
success: function(){
alert(data);
alert('Thanks for the vote!'); //for debug. Alert is showing! Still not submitting data to database though.
$('.line-items-rows').fadeOut('fast').delay(1000).fadeIn('fast');
}
});
});
});
这是回调 PHP 函数(它没有按应有的方式更新数据库):
function cb_lud_arrow_callback(){
//Redefine basic variables
global $wpdb;
$cb_lud_prefix = $wpdb->prefix;
$cb_lud_table = $cb_lud_prefix . 'cb_list_up_down';
//find the values posted to the form
$cb_lud_arrow_keys = array_keys($_POST['arrow']);
$cb_lud_arrow_values = array_values($_POST['entryID']);
$cb_lud_entry_id = (int)$cb_lud_arrow_values[2];
//set some variables to "up" or "down" depending on form input.
if (strpos($cb_lud_arrow_keys[2], 'up-ID') > 0) {
$cb_lud_arrow_direction = "up";
}
else if (strpos($cb_lud_arrow_keys[2], 'down-ID') > 0) {
$cb_lud_arrow_direction = "down";
}
else {
$cb_lud_arrow_direction = "nothing";
}
//Create the update query that will record the up and down votes.
//Up votes
if ($cb_lud_arrow_direction == "up" && $cb_lud_arrow_direction != "nothing") {
$wpdb->query('UPDATE '.$cb_lud_table.' SET up_votes=up_votes+1
WHERE entry_ID='.$cb_lud_entry_id.'');
}
//Down votes
else if ($cb_lud_arrow_direction == "down" && $cb_lud_arrow_direction != "nothing") {
$wpdb->query('UPDATE '.$cb_lud_table.' SET down_votes=down_votes+1
WHERE entry_ID='.$cb_lud_entry_id.'');
}
die(); // this is required to return a proper result
}