从AJAX

时间:2016-10-04 21:58:37

标签: javascript php jquery json ajax

我正在尝试通过POST调用PHP文件,并在调用的AJAX代码中检索其结果。但不幸的是它似乎没有用。在摆弄我的代码后,我得到“未定义”,“页面重新加载”或“控制台中的错误,我的参数在成功函数中使用的未定义”

这是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,
    });

现在我获得了调用此ajax函数的页面的完整HTML代码

我试图在ajax请求中设置aysnc: false,但它没有帮助,总是获取源代码的html代码(调用ajax函数)。

至于现在,我正在转向不需要返回数据的不同方法。但感谢您的帮助

1 个答案:

答案 0 :(得分:0)

由于

,浏览器尝试执行服务器响应
header("Content-Type: application/x-javascript");

更改为

header("Content-Type: application/json");