1、前端js正常ajax請求
<script>
function testGet(){
$.ajax({
url: "http://xxxx.com/home/signin/getxxx?session_id=xxxx",
type: "get",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}
function testPost(){
$.ajax({
url: "http://xxx.com/home/signin/getxxx",
type: "post",
dataType: "json",
data: {
session_id: 'xxxxx'
},
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}
</script>
后端php返回
jsonResponse($respone);
//jsonResponse方法:
//function jsonResponse($data)
//{
// exit(json_encode($data, JSON_UNESCAPED_SLASHES));
//}
2、前端js用ajax跨域請求
<script>
function testGet(){
$.ajax({
url: "http://xxxx.com/home/signin/getxxx?session_id=xxxx",
type: "get",
dataType: "jsonp",
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}
function testPost(){
$.ajax({
url: "http://xxx.com/home/signin/getxxx",
type: "post",
dataType: "jsonp",
data: {
session_id: 'xxxxx'
},
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}
</script>
thinkphp返回
$this->ajaxReturn($res,JSONP);
ajaxReturn方法:
/**
* Ajax方式返回數據到客戶端
* @access protected
* @param mixed $data 要返回的數據
* @param String $type AJAX返回數據格式
* @return void
*/
protected function ajaxReturn($data,$type='') {
if(empty($type)) $type = C('DEFAULT_AJAX_RETURN');
switch (strtoupper($type)){
case 'JSON' :
// 返回JSON數據格式到客戶端 包含狀態信息
header('Content-Type:application/json; charset=utf-8');
exit(json_encode($data));
case 'XML' :
// 返回xml格式數據
header('Content-Type:text/xml; charset=utf-8');
exit(xml_encode($data));
case 'JSONP':
// 返回JSON數據格式到客戶端 包含狀態信息
header('Content-Type:application/json; charset=utf-8');
$handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
exit($handler.'('.json_encode($data).');');
case 'EVAL' :
// 返回可執行的js腳本
header('Content-Type:text/html; charset=utf-8');
exit($data);
}
}