【问题标题】:ajax json php not workingajax json php不工作
【发布时间】:2014-08-31 16:23:22
【问题描述】:

我有一个可以发表评论的脚本。一切正常,但我需要它,所以如果发现 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');

【问题讨论】:

  • 使用回声一次...将两个数组绑定在一起...就像一个 json 对象 thrn 编码并返回

标签: php jquery ajax json


【解决方案1】:

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

来自PHP manual

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' =&gt; '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
});

阅读 jQuery documentation 以了解 AJAX 调用。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 它需要是 2 个数组,不是吗?
    • 不应该只返回一个数组
    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多