s***@sohu.com
s***@sohu.com
  • 发布:2016-12-04 01:50
  • 更新:2016-12-08 19:13
  • 阅读:3831

【报Bug】JSON.parse解析json字符串错误

分类:HTML5+

详细问题描述
[内容]
在html+的环境里,JSON.parse无法解析正常的json字符串

{       
    var xhr=new plus.net.XMLHttpRequest();  
    xhr.open("GET","http://mao.s1.natapp.cc/index.php/IWanMao/Home/getcontent/t/f/pageindex/1");  
    xhr.onreadystatechange=function(){  
        if(xhr.readyState==4&&xhr.status==200){  
            var res=xhr.responseText; //res为:‘{"eid":"397"}’  
            console.log(typeof res);  
            console.log(res);  
            var abc=JSON.parse(res);  
            console.log(abc);  
            console.log(abc.eid);     
        }  
    }  
    xhr.send();  
}  
document.addEventListener("plusready",myready,false);

解析不出来,报错:

string at index.html:27
{"eid":"397"} at index.html:28
SyntaxError: Unexpected token  in JSON at position 0
string at index.html:27
{"eid":"397"} at index.html:28
SyntaxError: Unexpected token  in JSON at position 0

在谷歌浏览器,用的js自带的xmlhttprequest,函数一样,正常,结果如下:

string
asa.html:20 {"eid":"397"}
asa.html:22 Object {eid: "397"}
asa.html:23 397

2016-12-04 01:50 负责人:无 分享
已邀请:
赵梦欢

赵梦欢 - 专注前端,乐于分享!

检查一下你返回的字符串前是不是有个空格;

var res=xhr.responseText;  
console.log(res[0]);   
var abc = JSON.parse(res.trim());  
console.log(abc[0].eid);
s***@sohu.com

s***@sohu.com (作者)

res的值为: `javascript {"eid":"397"}


标准json字符串,谷歌正常解析
s***@sohu.com

s***@sohu.com (作者)

解决了,谢谢,就是很奇怪,为什么会多了个空格.....

该问题目前已经被锁定, 无法添加新回复