douhan9467 2010-03-02 17:13
浏览 177
已采纳

当PHP响应头包含“application / json”时,JSON.parse在jQuery中失败

I'm getting a bit of a headache trying to figure this one out. To request some json-data from a PHP-script via Ajax, I'm using the jQuery function:

$.ajax({
    type: 'GET',
    cache: 'false',
    url: ajaxUrl,
    data: dataString,
    success: updatePage
});

If I don't set content-type in the PHP header to:

header('Content-type: application/json');

Then my response from the server looks like this:

{"content":"new content"}

And the content-type is automatically set to text/html. When dataType in the jQuery ajax options is unset, it uses a default of 'intelligent guessing'. I'm strongly assuming that jQuery recognizes the response-data as json because updatePage is parsed an object. updatePage uses the JSON js library(json2.js), and does this:

function updatePage(data) {
  $dataObj = JSON.parse(data); 
}

When the function is called upon ajax succes, everything works fine. No errors. Here's the strange thing, if I set my header to application/json as above, JSON.parse suddenly reports an error. The exact same error happens if i set my dataType to 'json' in the jQuery ajax request. The response I get from the PHP script when changing these things looks exactly like the one above. The error looks like this in Firebug:

JSON.parse
  $dataObj = JSON.parse(data); 

Kind of a long one, sorry, but If anyone knows what is wrong their help is greatly appreciated. Thanks for your time.

  • 写回答

1条回答 默认 最新

  • duan0530 2010-03-02 17:29
    关注

    It's because you end up trying to double-parse the return value.

    Both the explicit json data type and usage of the application/json MIME type cause jQuery to parse the returned string into a JavaScript object for you.

    So, your usage of JSON.parse(), in these cases, is superfluous.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制