加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

蛋疼的JSONP

发布时间:2020-12-16 19:19:19 所属栏目:百科 来源:网络整理
导读:test.php内容如下: ?phpecho'["hello","yes"]'; test.html内容如下: !DOCTYPEhtmlhtmlheadtitleTEST/titlemetacontent="text/html;charset=UTF-8"http-equiv="Content-Type"/scriptsrc="http://code.jquery.com/jquery-1.6.1.min.js"/script/headbodybutto

test.php内容如下:

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

test.html内容如下:

<!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串,所以解析之后不正确。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读