我正在开发一个评分系统。我的HTML
<div class="item-vote-wrapper" data-itemid="0">
<i class="far fa-thumbs-up fa-1.5x" data-index="0"></i>
<i class="far fa-thumbs-up fa-1.5x" data-index="1"></i>
<i class="far fa-thumbs-up fa-1.5x" data-index="2"></i>
</div>
在这里,我要为每个要投票的项目创建一个新的数据项。我的Jquery是
$('.fa-thumbs-up').on('click', function(){
ratedIndex = parseInt($(this).data('index'));
ratedArray[item_id] = ratedIndex;
localStorage.setItem('ratedArray', JSON.stringify(ratedArray));
// prepare data to be send to DB
let data_for_ajax = new FormData();
// $(this).parent() - is the parent of this <i> element, meaning div with class "item-vote-wrapper"
let item_id = $(this).parent().data('itemid');
// $(this) is the <i> element that was clicked
let vote = $(this).data('index');
// Append values to our data object
// data_for_ajax.append('parameter_name', parameter_value);
data_for_ajax.append('item_id', item_id);
data_for_ajax.append('vote_given', vote);
// debug form data
for (var pair of data_for_ajax.entries()) {
console.log("data_for_ajax entry: " + pair[0]+ ', ' + pair[1]);
}
saveToTheDB(data_for_ajax);
});
然后我与
建立连接 function saveToTheDB(data_for_ajax){
$.ajax({
url: "betrayal.php",
method: "POST",
data: data_for_ajax,
// By default jquery processes data and serializes it into a string
// By using a FormData object, we don't need this step, therefore we disable it
processData: false,
// Server returns a status code between 200 and 399
success: function(response) {
// This code will execute only when the request succeded
console.log("Success!");
},
// Server returns a status code between 400 and 505
error: function(jqXHR, textStatus, errorThrown){
console.log("An error occured. Request ended with status: " + textStatus);
console.log(jqXHR);
}
});
}
现在的问题是,当我在PHP中使用isset()检查item_id和vote_given时
<?php
function respond($status, $arr = array()){
// add our status, to final answer
$arr['status'] = $status;
if ($status != 'success'){
if ($status != 'internal_server_error'){
// Specific to server side errors
header("HTTP/1.1 500 Internal Server Error");
} else {
// Specific to client side errors
header("HTTP/1.1 400 Bad Request");
}
}
echo json_encode($arr, JSON_PRETTY_PRINT);
exit();
}
if (isset($_POST['item_id'], $_POST['vote_given'])){
// ...
} else {
respond(
'error',
array(
'message' => 'POST data is missing'
)
);
}
它返回POST数据丢失,并且分别检查item_id和表决_给定后,我可以知道它们均未设置。这是因为缺少json转换吗?