AJAX跨域请求 json 数据 (javascript,mootools,jquery) 示例我们都知道,AJAX的一大限制是不允许跨域请求。
AJAX跨域请求 json 数据 (javascript,mootools,jquery) 示例
我们都知道,AJAX的一大限制是不允许跨域请求。 不过通过使用JSONP来实现。 JSONP是一种通过脚本标记注入的方式,它是可以引用跨域URL的js脚本,不过需要提供一个回调函数(必须在您自己的页面上),因此,你可以自己处理结果。 让我们看看JSONP的是怎么在jQuery,MooTools的,Dojo Toolkit中实现的。?
?
jQuery的JSONPjQuery.getJSON方法:
?
jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{q: "Arsenal"},function(tweets) {// Handle response hereconsole.info("Twitter returned: ",tweets);});?
或者 类似
?
$.ajax({type:"get",data:"random="+Math.random(),url:url,dataType:"jsonp",jsonp:"callback",success:function(data){ $.each(data, function(key, val) { $("#myDiv").html($("#myDiv").html()+val.cvalue+"</br>"); });}});?
回调方法的参数 通过 getJSON 就可以获取 到 json对象
?
MooTools JSONPMooTools 需要 Request.JSONP Class , 可以从这里下载 MooTools More.? 选择 Request.JSONP,
这样 从另一个域获取json就是小菜一碟了.
?
new Request.JSONP({url: "http://search.twitter.com/search.json",data: {q: "Arsenal"},//提交的参数, 没有参数可以不写 callbackKey: 'jsoncallback',//自己定义回调函数的参数名称? onComplete: function(tweets) {// Log the result to console for inspectionconsole.info("Twitter returned: ",tweets);}}).send();?如果自己定义了回调函数的参数名称. 跟jquery一样.
?
服务器端你需要这样去取得:
?
String callback = request.getParameter("jsoncallback");//取得回调方法名response.setHeader("Cache-Control", "no-cache");response.setContentType("text/json;charset=UTF-8");PrintWriter out;try {out = response.getWriter();out.print(callback+"("+message+")");//这里是关键.主要就是这里out.flush();out.close();} catch (IOException e) {e.printStackTrace();}?
顺便说一句: 个人比较喜欢mootools的语法结构,和框架设计思路. 再次赞美!
?
Dojo JSONPJSONP 在 Dojo Toolkit 中需要用上 dojo.io.script (点击可以查看示例)
?
?
// dojo.io.script is an external dependency, so it must be requireddojo.require("dojo.io.script");// When the resource is readydojo.ready(function() {// Use the get methoddojo.io.script.get({// The URL to get JSON from Twitterurl: "http://search.twitter.com/search.json",// The callback paramatercallbackParamName: "callback", // Twitter requires "callback"// The content to sendcontent: {q: "Arsenal"},// The success callbackload: function(tweetsJson) { // Twitter sent us information!// Log the result to console for inspectionconsole.info("Twitter returned: ",tweetsJson);}});});?
JSONP是一种非常有效的,可靠的,容易实现的远程数据获取方式。 JSONP的策略也使开发人员能够避免繁琐的服务器代理方式,很方便的获取数据。 你可以自己写一个试试
?
