jquery中使用ajax jsonp的方法和注意事项

xiaoxiao2022-06-14  46

今天帮同事调试了下jquery中使用ajax jsonp方式,导致众多问题的原因是没有理解jquery中jsonp的本质。

查看了jquery源码后才知道他是添加脚本方式,但添加是的直接执行的方法,这个方法是jquery动态生成的,通过参数传递到后台的,后台通过request获得并以该参数值作为方法名,把json数据当成变量,加载完srcipt标签后直接执行该函数。

例如:

jsonp1251707322751({"name":"lava","nick":"\u6bd4\u76ee\u9c7c","contact":{"MSN":"lavaguo#msn.com","email":"guo.feng#zol.com.cn","website":"http:\/\/www.zol.com.cn"}})

 

jsonp1251707322751就是jquery动态生成的方法名,jsonp1251707322751()就是执行这个方法,里面的json就是参数了。

所以后台直接返回一个json是无法解析的,而且方法名必须是jquery动态生成的,如果是自己定义的则无法打开链接,火狐下报错为:

Access to restricted URI denied" code: "1012  xhr.open(type, s.url, s.async);\n 请求url格式为 http://xxx?callback =?",后端request获取参数为callback 下面是引用了网上的一个测试页面

 

<html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> </head> <body> <script type="text/javascript"> function aa() { alert("aa message!"); } function do_jsonp() { $.getJSON("http://active.zol.com.cn/guofeng/profile2.php?callback=?", function(data) { $('#result').val('My name is: ' + data.nick); }); } </script> <a href="javascript:do_jsonp();">Click me</a><br /> <textarea id="result" cols="50" rows="3"></textarea> </body> </html>  
转载请注明原文地址: https://www.6miu.com/read-4936547.html

最新回复(0)