Php Ajax未正确发送表单数据
我正在研究评级系统。我的HTMLPhp Ajax未正确发送表单数据,php,ajax,post,isset,Php,Ajax,Post,Isset,我正在研究评级系统。我的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>
<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>
我现在的问题是,当我在php中用isset()检查item_id和vote_时
<?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参数应该被调用vote\u
。您在JS代码中称之为vote
。您还应该使用json响应设置内容类型:application/json
头,但您没有这样做。第三,完全没有理由使用FormData
对象。一个简单的siple$.post(url,{item\u id:…,vote\u given:…})
将非常好。感谢Tomalak,我将编辑您推荐的内容,如果它有效,我将看到。非常感谢if(isset($\u POST['item\u id']&&$\u POST['vote\u given'])
您的第二个POST参数应该被调用vote\u given
。您在JS代码中称之为vote
。您还应该使用json响应设置内容类型:application/json
头,但您没有这样做。第三,完全没有理由使用FormData
对象。一个简单的siple$.post(url,{item\u id:…,vote\u given:…})
将非常好。感谢Tomalak,我将编辑您推荐的内容,如果它有效,我将看到。非常感谢<代码>如果(isset($\u POST['item\u id']&&$\u POST['vote\u given']))
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
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'
)
);
}