我試圖通過POST調用PHP文件並將其結果返回到調用AJAX代碼中。但不幸的是,它似乎並沒有工作。我的代碼周圍擺弄之後,我要麼得到「未定義」,「重新加載頁面」或「在控制檯中的錯誤,在成功的函數中使用我的參數沒有定義」從PHP調用從AJAX返回的JSON返回
這裏的Ajax代碼:
function postComment(formdata) {
if (formdata.comment != '') {
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
success: postSuccess(data), // function to handle the return
error: postError // function to handle errors
});
} else {
alert('Empty please write something!');
}
}
function postSuccess(data) {
console.log(data);
$('#commentform').get(0).reset();
displayComment(data);
}
,這裏是我的PHP處理程序:
$ajax = ($_SERVER['REQUESTED_WITH'] === 'XMLHttpRequest');
$added = add_comment($mysqli, $_POST); // contains an array
if ($ajax) {
sendAjaxResponse($added);
} else {
sendStandardResponse($added);
}
function sendAjaxResponse($added)
{
header("Content-Type: application/x-javascript");
if ($added) {
header('Status: 201');
echo(json_encode($added));
} else {
header('Status: 400');
}
}
這是添加看起來像PHP:
$added = array(
'id' => $id,//integer example: 90
'comment_post_ID' => $story_ID, //integer example: 21
'comment_author' => $author, //String example: Dominic
'comment' => $comment, //String example: This is a comment
'comment_date' => $date); //DateTime/String example: 08/02/2016 1970-01-01 00:00:00
個
最新通報
我改變了AJAX代碼如下:
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
success: postSuccess,
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
error: postError,
});
現在,我得到了網頁的全HTML的代碼調用這個AJAX功能
我試圖設置aysnc: false
在ajax請求,但它沒有幫助,總是得到源代碼的html代碼(調用ajax函數)。
至於現在我正在轉向另一種不需要返回數據的方法。但是,感謝您的幫助
'../../包括/ post_comment.php'不是一個網址 –
當您指定'success:postSuccess(data)'時,您正在_calling_'postSuccess',並且有一個不存在的'data'參數。 – jszobody
嘗試刪除'(數據)'。成功參數需要一個函數。您正在將該函數調用的結果提供給$ .ajax – Phil