ajax json php not working


ajax json php not working

我有一个脚本,它将发布一条注释。所有的工作,但我需要它,所以如果php中发现任何错误,它会提醒用户错误,否则它会显示注释

这是ajax部分

    $.ajax({
        type: 'POST',
        url: 'comment/post.php',
        data: ajaxData,
        processData: false,
        contentType: false,
        dataType: "json",
        success:function(result){
              if(result.error == true){
                   alert(result.error);
              } else {
                   $('#comments').prepend(result.comment);
              }
        }
});

和php(注意这只是一部分,但您应该理解)。因此,如果出现错误,它应该发出警报,否则应该发出评论。但不起作用

if(isset($_FILES['file'])){
        $image_key = sha1(uniqid(mt_rand(), true));
        $new_image_name = $image_key.'.jpg';
        move_uploaded_file($_FILES['file']['tmp_name'], '../uploads/'.$new_image_name);
        $file = '<img src="uploads/'.$new_image_name.'" />';
        $Comment->addImage($new_image_name, $random);
        echo json_encode(array('error' => true, 'Your file was too big'));
    } 
    echo json_encode(array('comment' => 'Here is your comment blah blah'));
    header('Content-type: application/json');

我在您发布的内容中看到的一个问题是,您必须在输出任何内容之前设置标题。因此,在PHP文件中,将header('Content-type: application/json');移动到文件的顶部,或者至少移动到任何输出的上方。否则,将不会设置内容类型标头。

来自PHP手册:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

另一个问题是,当请求成功时,您将输出两个单独的json_encoded数组。你应该只有一个(里面可以包含多个数组),所以调整你的代码如下:

if (isset($_FILES['file'])) {
    ...
    echo json_encode(array('error' => true, 'Your file was too big'));
                                            ^-- Are you missing an array index here for your comment?
} else {
    echo json_encode(array('comment' => 'Here is your comment blah blah'));
}

正如我的代码块中所指出的,看起来您的第一个数组可能缺少索引。你忘了包括"注释"(即'comment' => 'Your file was too big')了吗?

此外,为了使AJAX调用更加健壮,可以添加.done().fail()方法。示例:

$.post( "example.php", function() {
// your AJAX configuration
})
.done(function(data) {
// AJAX call succeeded, do something like process the data sent back
})
.fail(function(error, status, jqXHR) {
// AJAX call failed, do something like alert the user
});

阅读AJAX调用的jQuery文档。

首先删除php文件中的头,然后php返回2个数组,它不应该是