使用Jquery宽裕获取php数据,
方法一:使用jsonp获取另一个域名下的信息。
js请求代码:
$(function(){
$.ajax({
url:'http://domain.com/api/cors/jsonp.php',
type:'GET',
dataType:'jsonp',
jsonpCallback: 'callback',
success:function(data){
console.log(data);
},
error:function(data){
console.log('error');
}
});
});
php:返回代码:
if(isset($_GET['callback']))
{
$obj = array('user_name' => 'zhang3','password'=>'123456');
echo $_GET['callback']. '(' . json_encode($obj) . ');';
}
方法二:使用php允许跨域访问
在php中设置头部设置为Origin:*
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET');
header('Access-Control-Allow-Credentials:true');
echo json_encode($obj = array('user_name' => 'zhang3','password'=>'123456'));
前端请求:
$.ajax({
url:'http://domain.com/api/cors/jsonp.php',
type:'GET',
dataType:'json',
//jsonpCallback: 'callback',
success:function(data){
console.log(data);
},
error:function(data){
console.log('error');
}
});