Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

跨域处理之JSONP #1

Open
PLDaily opened this issue Nov 10, 2016 · 0 comments
Open

跨域处理之JSONP #1

PLDaily opened this issue Nov 10, 2016 · 0 comments

Comments

@PLDaily
Copy link
Owner

PLDaily commented Nov 10, 2016

关于前端的跨域问题一直都想去了解应该如何去解决,但由于没有实际例子,看了网上的很多例子一直都处于懵懂的状态,正好公司最近出了一个跨域的问题就随便学习总结了一下。

运用情景

情景说明:俩个子域名一个biz,一个user_center,后台使用thinkphp的框架,biz下的一个用户反馈的邮箱的方法写在user_center项目中,当点击邮箱要发送电子邮件的时候就涉及到了跨域。由于jquery的跨域只支持get的方式,不支持post,本文主要讲解jquery的get方式的跨域处理

前端JS脚本发起异步请求

$.ajax({
    type: 'get', //请求的方式
    url: 'http://user.cli.me/service/index/send',//请求的地址
    data: data,//传输的数据
    dataType: 'jsonp',
    jsonp: 'callback',
    jsonpCallback: 'abc',
    success:function(ret){
        //成功后的操作
    }
});

脚本在biz.cli.me的页面下,对user.cli.me的页面发起一个异步请求

后台thinkphp中的输出处理

public function send(){
	//对传过来data数据的处理操作省略
	$this->_ajax(1,'发送成功',4);
}
private function _ajax($status=null,$msg=null,$data=null){
	$arr['status'] = $status;
	$arr['data'] = $data;
	$arr['msg'] = $msg;
	if(isset($_GET['callback'])) {
		$callback = GET("callback");//获取callback,相当于客户端与服务端的一个通信
		$json = $this->_json($arr);
		$jsonp = $callback.'(' . $json . ')';
		echo $jsonp;
	}else {
		echo $this->_json($arr);
	}
	exit;
}
//转化成JSON数据
private function _json($arr){
	if(is_array($arr)) return json_encode($arr);
}

后台先是通过get获取前台的callback,形成前台与后台的通信。再是对需要返回的数据进行处理,使用jsonp形式输出。

成功返回后的结果

  1. 成功后返回的数据为
abc({"status":1,"data":4,"msg":"\u53d1\u9001\u6210\u529f"});

该数据只是示例,可以按自己的实际需求输出

  1. jsonpCallback设置为什么值则jsonp中的abc则显示为什么
  2. 前端脚本异步请求返回的数据
success: function(ret) {
	console.log(ret);//{status: 1, data: 4, msg: "发送成功"}	
}
@PLDaily PLDaily changed the title 跨域处理 跨域处理之JSONP Dec 17, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant