A-A+
jquery/js ajax 跨域4种方法
ajax跨域对于现在的web开发来讲用到非常的多同时现在关于ajax跨域的实现方法也不少了,下文来为各位整理4种ajax跨域实现方法,关于ajax跨域问题,今天整理了一下,其实还有其他办法了,个人推荐以下4种,请参考:ajax 跨域实例.
一,传统的ajax方法
1,js代码
- $("#ajax").click(function(){
- $.ajax({
- type: "POST",
- url: "/test2.php",
- data: 'name=ajax',
- dataType:"json",
- success: function(data){
- $('#Result').text(data.name);
- }
- });
- });
2,test2.php代码
- header("Access-Control-Allow-Origin:http://blog.51yip.com"); //允许blog.51yip.com提交访问
- //header("Access-Control-Allow-Origin:*"); //允许任何访问
- echo json_encode($_POST);
二,ajax jsonp
- $("#jsonp").click(function(){
- $.ajax({
- url: 'http://manual.51yip.com/test1.php',
- data: {name: 'jsonp'},
- dataType: 'jsonp',
- jsonp: 'callback', //为服务端准备的参数
- jsonpCallback: 'getdata', //回调函数
- success: function(){
- alert("success");
- }
- });
- });
- function getdata(data){
- $('#Result').text(data.name);
- }
2,test1.php
- <?php
- if(isset($_GET['name']) && isset($_GET['callback'])) //callback根js端要对应,不然会报错的
- {
- echo $_GET['callback']. '(' . json_encode($_GET) . ');'; //格式固定的,为什么这样,不清楚
- }
- ?>
三,$.getJSON
- $("#getjson").click(function(){
- $.getJSON('http://manual.51yip.com/test1.php?name=getjson&callback=?', function(data){ //没有回调函数,直接处理
- $('#Result').text(data.name);
- });
- });
四,$.getScript
- $("#getscript").click(function(){
- $.getScript('http://manual.51yip.com/test1.php?name=getscript&callback=getdata'); //回调函数根jsonp一样
- });
也可以通过查看例子源码,来查看JS代码