发布于 2016-12-26 11:03:36 | 145 次阅读 | 评论: 0 | 来源: 网友投递
JSONP 跨域解决方案
通过script标签来跨域获取数据,名为JSON with Padding,或者就叫JSONP。JSONP的原理很简单,但需要服务器端给予相应配合。大致来说,JSONP的实现思路就是在客户端编程时作好使用JSON数据的准备,然后再通过圆括号将这些数据括起来以创建一条有效的JavaScript语句(可能是一次有效的函数调用)。
class JsController extends CController {
public function actionIndex() {
$callback = isset($_GET['callback']) ? $_GET['callback'] : '';
$result = array();
$userinfo = Intf_Client_Uc_User::instance()->getLoginUser();
$cid = Everychina_Member::instance()->getCid($userinfo['uid']);
//公司展厅评分
$room_score = Ec_RoomScore::getInstance();
//获得展厅老的评分
$update_status = true;
//重新评分
if(isset($_GET['action']) && $_GET['action']=='update') {
$score_res = $room_score->getScoreInfo($cid);
$room_score->updateScoreResult($cid,$score_res);
$update_status = true;
}
$result['status'] = $update_status;
$res = $room_score->getScoreResult($cid);
$result['score'] = $room_score->getScoreResultView($res['score']);
if ($callback) {
$js = json_encode($result);
echo "$callback( ($js) );";
}
}
<a id="update_score" href="#" onclick="ajaxUpdateScore();return false;">update score</a>
<div id="member_score"></div>
function ajaxUpdateScore(){
if(document.getElementById("member_score_script")) {
var score_script = document.getElementById("member_score_script");
document.body.removeChild(score_script);
}
var score_script = document.createElement("script");
score_script.id = "member_score_script";
score_script.src = 'http://dev.members.everychina.com/index.php?r=js/index&callback=show_score&t='+new Date().getTime();
document.body.appendChild(score_script);
}
function show_score(json) {
if(json.status == true) {
var html = '<p>level:'+json.score.level+'</p>';
html += '<p>msg:'+json.score.msg+'</p>';
html += '<p>score:'+json.score.score+'</p>';
$("#member_score").html(html);
}
}