JSON跨域调用与动态脚本加载

下面是在anyjs中JSON跨域的实现(JSONP),原理很简单,动态生成script标签,没有使用到callback(可支持),需要与后台协调保持对象一致,anyjs默认采用JSONP。

01 anyjs.gjsonp=function(url,callbackfn){
02     var h=document.getElementsByTagName(‘head’)[0];
03     var s=anyjs.create(‘script’);
04     anyjs(s).set(‘type’, ‘text/javascript’).set(‘src’, url);
05     anyjs(h).apd(s);
06     if(anyjs.ie){ //IE6+
07             s.onreadystatechange = function () {
08             if (s.readyState == ‘loaded’ || s.readyState == ‘complete’) {
09                 (callbackfn)(JSONP);
10                 JSONP=null;
11                anyjs(s).rmv();
12             }
13         }
14     } else {//GECKOS、WEBKIT、ETC..
15             s.onload = function() {
16             (callbackfn)(JSONP);
17             JSONP=null;
18             anyjs(s).rmv();
19         }
20     }
21     return false;
22 };//end

使用anyjs跨域调用示例:

01 //JSONP跨域测试开始
02 $(“#jsonp”).click(function(){
03 y=$.create(“div”);
04 $(y).set(“id”,“bglay”).set(“class”,“bglay”);
05 $(“body”).ist(y);
06 x=$.create(“div”);
07 $(x).set(“id”,“ajax”);
08 $(x).set(“class”,“ajax”);
09 $(“body”).ist(x);
10 $(“#ajax”).show();
11 $.gjsonp(“http://www.focusstudio.org/data.php?type=jsonp”,function(data){
12 var arr=[],str=“”;
13 for(var i=0;i<data.length;i++){
14
15 arr.push(data[i].a);
16 str+=data[i].b+“|”;
17 }
18 $(“#ajax”).h(arr.join(“‘”)+str);
19 });
20
21 $(“#ajax”).click(function(){$(“div.bglay”,“#ajax”).fout();$(“div.bglay”,“#ajax”).rmv();});
22 });
23 //跨域jsonp测试结束

后台相关代码:

1 <?php
2 header(“Content-Type:application/x-javascript; charset=utf-8″);
3 $callback = isset($_GET['callback']) ? $_GET['callback'] : ‘JSONP’;
4 $json=array(array(‘a’=>‘enimo1jsonp’,‘b’=>‘test1jsonp’),array(‘a’=>‘enimo2′,‘b’=>‘test2jsonp’));
5 echo ‘var ‘.$callback.‘=’.json_encode($json);
6 ?>

到这里,要实现动态加载js脚本,我想大家应该不言自明了吧。

可能有关的文章:

Tags : , , ,

Google Reader Yahoo Facebook Twitter Digg FriendFeed Delicious Google Translate
这篇日志发表于2010年05月25日 9:40 下午。 你可以订阅该日志的所有评论通过 RSS 2.0。 你可以发表评论,或者引用通告

1条回应

评论(1)引用通告(0)

  1. CookRosetta32

    Some time before, I really needed to buy a building for my organization but I did not earn enough money and couldn’t purchase anything. Thank God my fellow adviced to take the http://lowest-rate-loans.com from trustworthy creditors. Hence, I did so and was satisfied with my collateral loan.

    2010年05月27日 8:49 上午 | #1

发表评论

Anti-Spam Protection by WP-SpamFree

(Ctrl+Enter)

XHTML:你可以使用这些标签:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>