蛋疼的JSONP

前端之家收集整理的这篇文章主要介绍了蛋疼的JSONP前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

test.PHP内容如下:

<?PHP
echo'["hello","yes"]';

test.html内容如下:

@H_404_6@<!DOCTYPEhtml> <html> <head> <title>TEST</title> <Metacontent="text/html;charset=UTF-8"http-equiv="Content-Type"/> <scriptsrc="http://code.jquery.com/jquery-1.6.1.min.js"></script> </head> <body> <buttonid="test">TEST</button> <script> $(function(){ $("#test").click(function(){ $.ajax({ type:'POST',url:'http://xxxx.com/test.PHP',data:'text=你叫什么名字?',dataType:'JSONP',complete:function(data,status){ varjson=$.parseJSON(data.responseText); console.log('data:'+json[0]); } }); }); }); </script> </body> </html>

如上,test.PHP和test.html都放在xxxx.com

访问xxxx.com/test.html点击test按钮,结果是:

data: hello

符合预期结果。

把test.html放在oooo.com,以实现跨域AJAX,访问oooo.com/test.html点击按钮则显示

TypeError: json is null

console.log('data: ' + json[0]);

非常蛋疼。。。。


看了一些资料有点明白了,所谓的jsonp,并不是一种数据格式而是在json串前添加一个script标签,然后src指向那个url,见下文:

http://bbs.csdn.net/topics/390459676

因为本地请求并非跨域,所以直接返回json串没有额外添加什么标签,所以可以正常解析,但是跨域的时候返回的是非标准json串,所以解析之后不正确。

猜你在找的Json相关文章