蛋疼的JSONP

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

test.PHP内容如下:

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

test.html内容如下:

  1. <!DOCTYPEhtml>
  2. <html>
  3. <head>
  4. <title>TEST</title>
  5. <Metacontent="text/html;charset=UTF-8"http-equiv="Content-Type"/>
  6. <scriptsrc="http://code.jquery.com/jquery-1.6.1.min.js"></script>
  7. </head>
  8. <body>
  9. <buttonid="test">TEST</button>
  10. <script>
  11. $(function(){
  12. $("#test").click(function(){
  13. $.ajax({
  14. type:'POST',url:'http://xxxx.com/test.PHP',data:'text=你叫什么名字?',dataType:'JSONP',complete:function(data,status){
  15. varjson=$.parseJSON(data.responseText);
  16. console.log('data:'+json[0]);
  17. }
  18. });
  19. });
  20. });
  21. </script>
  22. </body>
  23. </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相关文章