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串,因此解析以後不正確。