蛋疼的JSONP

test.php内容如下:

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

test.html内容如下:

<!DOCTYPE html>
<html>
  <head>
    <title>TEST</title>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>   
       <script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
  </head>
  <body>
      <button id="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){
                    var json = $.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.youkuaiyun.com/topics/390459676

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

转载于:https://my.oschina.net/u/150705/blog/191540

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值