标签:
模拟服务器端的PHP文件:
service:
<?php
//允许访问
header(‘Access-Control-Allow-Origin:*‘);
@$callback=$_GET[‘callback‘];
//创建数据
$userInfo = array(‘id‘=>1,‘username‘=>‘Scott Jeremy‘,‘email‘=>‘673457942@qq.com‘);
//编译成JSON
$result = json_encode($userInfo);
echo $callback."({$result})";
service2:
<?php
header(‘Access-Control-Allow-Origin:*‘);
$userInfo = array(‘id‘=>1,‘username‘=>‘Scott Jeremy‘,‘email‘=>‘673457942@qq.com‘);
echo json_encode($userInfo);
原生Javascript:
function jsonpCallback(result) {
//alert(result);会返回jsonpCallback({"id":1,"username":"Scott Jeremy","email":"673457942@qq.com"})
alert(‘My :‘+result.username+‘.‘+‘My email:‘+result.email);
}
//创建script标签
var script = document.createElement(‘script‘);
//定义script标签的url
script.src = ‘http://localhost/service.php?callback=jsonpCallback‘;
//把标签放到head中
document.getElementsByTagName(‘head‘)[0].appendChild(script);
利用jQuery实现跨域请求有三种方法:
1:AJAX请求
$(‘#btn1‘).on(‘click‘,function () {
$.ajax({
//设置url
url:‘http://localhost/service2.php‘,
//用什么方式请求
type:‘GET‘,
//返回来用什么形式解析
dataType:‘json‘,
success:function (data) {
alert(data.username);
alert(data.email);
},
error:function () {
alert(‘error‘);
}
});
});
2:JSONP实现跨域请求
$(‘#btn2‘).on(‘click‘,function () {
$.ajax({
url:‘http://localhost/service.php‘,
type:‘GET‘,
dataType:‘JSONP‘,
//JSONP回调函数名
jsonp:‘callback‘,
//JSONP回调后的JSON名,相当于JSON文章中的book
jsonpCallback:‘Jeremy‘,
success:function (data) {
alert(data.username);
alert(data.email);
}
})
});
3:getJSON(最简单的一种:缩写)
$(‘#btn3‘).on(‘click‘,function () {
$.getJSON(‘http://localhost/service.php?callback=?‘,function (data) {
alert(data.username);
alert(data.email);
})
});
标签:
原文地址:http://www.cnblogs.com/scottjeremy/p/5814141.html