web三种跨域请求数据方法

以下测试代码使用php,浏览器测试使用IE9,chrome,firefox,safari

<! DOCTYPE HTML >
< html >
< head >
     < meta  charset ="UTF-8" >
     < script  type ="text/javascript"  src ="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" ></ script >
     < script  type ="text/javascript"  id ="loadjson" ></ script >
     < script  type ="text/javascript" >
    
//  第一种
     //  test1.php在服务器设置请允许跨域(注意:IE9测试不通过)
    $.ajax({
           type: 'POST',
           url: 'http:
// 127.0.0.1:8081/test/test1.php',
           data: 'name = penngo',
           dataType: 'json',
           success: 
function (msg){
              $('#json').html(JSON.stringify(msg));
           }
        });

    
/*  
    第二种JSONP:
    在客户端动态注册一个函数function test(data),然后将函数名传到服务器,服务器返回一个test({json})到客户端运行,这样就调用客户端的function test(data),从而实现了跨域,jquery已经支持jsonp
    
*/
    
//  test2.php使用jsonp
    $.ajax({
           type: 'GET',
           url: 'http:
// 127.0.0.1:8081/test/test2.php?callback=?',
           data: 'name = penngo',
           dataType: 'jsonp',
           success: 
function (msg){
              $('#jsonp').html(JSON.stringify(msg));
           }
        });

    
/*
    第三种,原理与jsonp类似,web页面上调用js文件时不受跨域影响,
    只要利用<script>标签的src属性,动态加载js方式就能跨域,该方式为异步,通过testjs()回调
    
*/
    
var  testjs  =   function (msg){
         $('#js').html(JSON.stringify(msg));
    }
    $('#loadjson')[
0 ].src  =  'http: // 127.0.0.1:8081/test/test3.php?method=testjs&name=penngo';
     </ script >

</ head >
< body >
    header跨域:
     < div  id ="json" >
        
     </ div >
     < br />
    jsonp跨域:
     < div  id ="jsonp" >
        
     </ div >
     < br />
    js请求实现跨域:
     < div  id ="js" >
        
     </ div >
</ body >
</ html >

服务器端处理
test1.php
<?php
     header("Access-Control-Allow-Origin: *");
     $name =  $_REQUEST['name'];
     $result =  array('success'=>1, 'name'=> $name);
     echo json_encode( $result);
?>

test2.php
<?php
     $callback =  $_REQUEST['callback'];
     $name =  $_REQUEST['name'];
     $result =  array('success'=>1, 'name'=> $name);
     $jsonData = json_encode( $result);
     echo  $callback . "(" .  $jsonData . ")";
?>

test3.php
<?php
     $method =  $_REQUEST['method'];
     $name =  $_REQUEST['name'];
     $result =  array('success'=>1, 'name'=> $name);
     $jsonData = json_encode( $result);
     header('Content-type:application/x-javascript');
     echo "$method($jsonData);";
?>



IE9测试,页面输出内容
header跨域: 
jsonp跨域: 
{"success":1,"name":"penngo"}
js请求实现跨域: 
{"success":1,"name":"penngo"}
chrome,firefox,safari测试,页面输出内容
header跨域:
{"success":1,"name":"penngo"}
jsonp跨域:
{"success":1,"name":"penngo"}
js请求实现跨域:
{"success":1,"name":"penngo"}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值