蛋疼的JSONP

test.php内容以下:php

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

test.html内容以下: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.comjquery

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

data: hellojson

符合预期结果。跨域

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

TypeError: json is nullui

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

很是蛋疼。。。。spa


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

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

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

相关文章
相关标签/搜索