A-A+

jquery/js ajax 跨域4种方法

2016年01月12日 前端设计 暂无评论 阅读 5 views 次

ajax跨域对于现在的web开发来讲用到非常的多同时现在关于ajax跨域的实现方法也不少了,下文来为各位整理4种ajax跨域实现方法,关于ajax跨域问题,今天整理了一下,其实还有其他办法了,个人推荐以下4种,请参考:ajax 跨域实例.

一,传统的ajax方法

1,js代码

  1. $("#ajax").click(function(){    
  2.  $.ajax({    
  3.  type: "POST",    
  4.  url: "/test2.php",    
  5.  data: 'name=ajax',    
  6.  dataType:"json",    
  7.  success: function(data){    
  8.  $('#Result').text(data.name);    
  9.  }    
  10.  });    
  11.  });   

2,test2.php代码

  1. header("Access-Control-Allow-Origin:http://blog.51yip.com");    //允许blog.51yip.com提交访问    
  2. //header("Access-Control-Allow-Origin:*");    //允许任何访问    
  3. echo json_encode($_POST);   

二,ajax jsonp

  1. $("#jsonp").click(function(){    
  2.  $.ajax({    
  3.  url: 'http://manual.51yip.com/test1.php',    
  4.  data: {name: 'jsonp'},    
  5.  dataType: 'jsonp',    
  6.  jsonp: 'callback',      //为服务端准备的参数    
  7.  jsonpCallback: 'getdata',   //回调函数    
  8.  success: function(){    
  9.  alert("success");    
  10.  }    
  11.  });    
  12.  });    
  13.     
  14. function getdata(data){    
  15.  $('#Result').text(data.name);    
  16. }  

2,test1.php

  1. <?php    
  2.  if(isset($_GET['name']) && isset($_GET['callback']))   //callback根js端要对应,不然会报错的    
  3.  {    
  4.  echo $_GET['callback']. '(' . json_encode($_GET) . ');';   //格式固定的,为什么这样,不清楚    
  5.  }    
  6. ?>  

三,$.getJSON

  1. $("#getjson").click(function(){    
  2.  $.getJSON('http://manual.51yip.com/test1.php?name=getjson&callback=?', function(data){  //没有回调函数,直接处理    
  3.  $('#Result').text(data.name);    
  4.  });    
  5. });  

四,$.getScript

  1. $("#getscript").click(function(){    
  2.  $.getScript('http://manual.51yip.com/test1.php?name=getscript&callback=getdata');  //回调函数根jsonp一样    
  3. });   

也可以通过查看例子源码,来查看JS代码

给我留言