Maison >interface Web >js tutoriel >JSONP 跨域共享信息_json
由于同源策略,一般来说位于 server1.example.com 的网页无法与不是 server1.example.com 的服务器沟通,而 HTML 的 <script> 元素是一个例外。利用 <script> 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。用 JSONP 抓到的资料并不是 JSON,而是任意的 JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析。 <br><br>下面是我在一个项目中的应用: <br><br>描述:域名dev.uc.everychina.com 要获得域名 dev.members.everychina.com下的数据 <BR>dev.members.everychina.com的服务器端代码: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="93218" class="copybut" id="copybut93218" onclick="doCopy('code93218')"><U>复制代码 代码如下:<div class="codebody" id="code93218"> <BR>class JsController extends CController { <BR>public function actionIndex() { <BR>$callback = isset($_GET['callback']) ? $_GET['callback'] : ''; <BR>$result = array(); <BR>$userinfo = Intf_Client_Uc_User::instance()->getLoginUser(); <BR>$cid = Everychina_Member::instance()->getCid($userinfo['uid']); <BR>//公司展厅评分 <BR>$room_score = Ec_RoomScore::getInstance(); <BR>//获得展厅老的评分 <BR>$update_status = true; <BR>//重新评分 <BR>if(isset($_GET['action']) && $_GET['action']=='update') { <BR>$score_res = $room_score->getScoreInfo($cid); <BR>$room_score->updateScoreResult($cid,$score_res); <BR>$update_status = true; <BR>} <BR>$result['status'] = $update_status; <BR>$res = $room_score->getScoreResult($cid); <BR>$result['score'] = $room_score->getScoreResultView($res['score']); <BR>if ($callback) { <BR>$js = json_encode($result); <BR>echo "$callback( ($js) );"; <BR>} <BR>} <BR> <BR>域名 dev.uc.everychina.com 下,前端调用(html) <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="84932" class="copybut" id="copybut84932" onclick="doCopy('code84932')"><U>复制代码 代码如下:<div class="codebody" id="code84932"> <BR><a id="update_score" href="#" onclick="ajaxUpdateScore();return false;">update score <BR><div id="member_score"> <BR> <BR>javascript <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="62906" class="copybut" id="copybut62906" onclick="doCopy('code62906')"><U>复制代码 代码如下:<div class="codebody" id="code62906"> <BR> function ajaxUpdateScore(){ <BR>if(document.getElementById("member_score_script")) { <BR>var score_script = document.getElementById("member_score_script"); <BR>document.body.removeChild(score_script); <BR>} <BR>var score_script = document.createElement("script"); <BR>score_script.id = "member_score_script"; <BR>score_script.src = 'http://dev.members.everychina.com/index.php?r=js/index&callback=show_score&t='+new Date().getTime(); <BR>document.body.appendChild(score_script); <BR>} <BR>function show_score(json) { <BR>if(json.status == true) { <BR>var html = '<p>level:'+json.score.level+'</script>
';msg:'+json.score.msg+'
';score:'+json.score.score+'
';