为什么总是jQuery Ajax JSON请求失败?

时间:2013-10-19 15:03:05

标签: php ajax json jquery

我目前有一个代码片段,我想用它来获取Ajax调用并从我的PHP文件中返回JSON数据,我可以在jQuery方面使用它。我的问题是,如果我将数据类型更改为JSON,我总是会在请求中收到错误,但是当我在Firebug中检查它时,我可以看到PHP文件刚刚返回了JSON值!

这是HTML:

<form id="formm" method="post">
    <input type="text" name="test" value="" id="test"/>
    <input type="submit" name="submit" value="Submit"/>
</form>

<div id="result"></div>

这是JS:

$("#formm").submit(function(event) {

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get some values from elements on the page: */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div */
    $.ajax({
        url: "functions.php",
        type: "post",
        dataType: "json",
        data: values,
        success: function(data) {
            alert(data);
        },
        error:function(){
            alert("failure");
            $("#result").html('There is error while submit');
        }
    });
});

PHP文件:

echo json_encode(array('returned_val' => $_POST['test']));

当我使用Firebug进行检查时,我得到:returned_val“无论我在文本框中输入什么内容”。谁能告诉我可能是什么问题?

更新:

响应标题:

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language ***
Content-Length  5
Content-Type    application/json; charset=utf-8
Host    localhost
Referer http://localhost/test/
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
X-Requested-With    XMLHttpRequest

当我把错误放在控制台中时,我明白了:

  

发生以下错误:parsererror SyntaxError:JSON.parse:   意外的角色

1 个答案:

答案 0 :(得分:6)

以严格的方式解析JSON数据;任何格式错误的JSON都会被拒绝,并抛出一个解析错误。从jQuery 1.9开始,空响应也被拒绝;服务器应返回null或{}的响应

这是文档http://api.jquery.com/jQuery.ajax/

所以从php检查你的json响应(json数据是否格式正确且非空)