模拟服务器端的PHP文件:
service:
<?php//允许访问header(‘Access-Control-Allow-Origin:*‘);@$callback=$_GET[‘callback‘];//创建数据$userInfo = array(‘id‘=>1,‘username‘=>‘Scott Jeremy‘,‘email‘=>‘[email protected]‘);//编译成JSON$result = json_encode($userInfo);echo $callback."({$result})";
service2:
<?phpheader(‘Access-Control-Allow-Origin:*‘);$userInfo = array(‘id‘=>1,‘username‘=>‘Scott Jeremy‘,‘email‘=>‘[email protected]‘);echo json_encode($userInfo);
原生Javascript:
function jsonpCallback(result) { //alert(result);会返回jsonpCallback({"id":1,"username":"Scott Jeremy","email":"[email protected]"}) alert(‘My :‘+result.username+‘.‘+‘My email:‘+result.email);}//创建script标签var script = document.createElement(‘script‘);//定义script标签的urlscript.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); })});
时间: 2024-10-10 15:47:01