随身笔记
随身笔记

jquery ajax 跨域实例

跨域案例下载:https://sdeno.com/?p=4815

 

先看下jsonp原理

https://sdeno.com/wp-content/uploads/2015/03/QQ截图20240409094428-1024x244.jpg

 

例子:

http://www.weather.com.cn/data/cityinfo/101200101.html

天气预报提供对外接口,供各大网站获取其数据,属于跨域问题。

由于提供的接口本身没有回调函数只是简单的一段字符串,我们不能直接使用前端技术获取到数据,所以要配合php将接口进行简单的处理。

1,服务器设置

callback1
<?php 
 header("content-type: text/html"); 
 $url = 'http://www.weather.com.cn/data/cityinfo/101200101.html'; //接口没有提供回调函数所以只能自己写回调 
 $data = file_get_contents($url); 
 $str='nini'.'('.$data.')'; //将数据放入到函数值中 
 //或者 $str=$_POST['wowo'].'('.$data.')';
 echo $str;
?>

2,前端设置

$.ajax({
  type:'post', //不声明默认是get
  url:'http://127.0.0.1/2.php', //需要跨域请求的地址
  dataType:"jsonp", //必须是jsonp 才有回调函数返回
  jsonp:"wowo", //自定义回调函数名,如果没定义默认名为 callback
  jsonpCallback:"nini", //自定义回调函数值,如果没有定义将会是随机生成
  error: function(){
    alert("ERROR!")
  },
  success: function(msg){
   alert(msg.weatherinfo.city);
   }
 });

返回来的msg参数就是封装好的接口对象,这样就能实现跨域访问到其他网站的数据。

 

—————————————-js jquery 跨域 推荐看以下部分——————————————————–

以下环境讲解,是在跨域情况下

客户端:

$('button').click(function(){
  $.ajax({
    type:'POST', //虽然设置了post,跨域时候服务器端才是以get方式接收
    url:"http://localhost/server.php", //虽然存在跨域,服务器端还是能接受到客户端发送来的数据,但是客户端接受不到服务器端返回的数据,被浏览器挡住了
    data:{user:'root',pass:'187'}, //这里是客户端要发送给服务器的数据,也就是服务器要接受的数据,这些数据不管存不存在跨域情况,服务器都能接受的到用$_GET[]方式接受
    dataType:"jsonp", //跨域接受服务器返回的数据,必须是jsonp类型才行
    cache:false,
    // jsonp:"wowo", //如果这两项没有设置,默认发送给服务器地址是:server.php?callback=jQuery18302435384537538523_1476780843978&user=root&pass=187
    // jsonpCallback:"nini", //如果设置了发送给服务器的请求是:server.php?wowo=nini&user=root&pass=187
          //以上两项设置其中一项就行了,如果设置了jsonp:"wowo",服务器就用$_GET['wowo']([{},{}])来接收;设置了jsonpCallback,直接就 nini([{},{}])
    success: function(data){
      alert('能获取服务器返回的信息,跨域成功'); //这里的回调触发,只有客户端成功接受到了data,就是url返回的数据才能发出到。
    }
  });
  return false;
});

 

服务器端:

header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect('localhost', 'root', '', 'test2');
mysqli_query($con, "insert into liuyan_user(liuyan_username,liuyan_userpass) values ('".$_GET['user']."','".$_GET['pass']."')"); //跨域时,数据发送给服务器都是以get方式发送的
 
 
$data='[{name:"chenge"},{age:24}]'; //这里就是要返回给客户端的数据,必须还是json格式的,不然就出错。之前设置了也必须设置dataType:"jsonp"
$str=$_GET['wowo'].'('.$data.')';
//这里其实就是 'jQuery18302435384537538523_1476780843978([{name:"chenge"},{age:24}])' ,直接把这个结果输出,客户端就能接收到了,因为jquery已经封装好了。
//如果设置了jsonpCallback:"nini",直接就 'nini([{name:"chenge"},{age:24}])'
echo $str;  //'jQuery18302435384537538523_1476780843978([{name:"chenge"},{age:24}])'

 

 

以上方法,貌似只能支持谷歌、火狐。遇到IE就完全不能兼容了。但是IE8、9有专门插件兼容。

推荐查看https://sdeno.com/?p=6218  ,兼容ie6/7/8浏览器。

jquery.xdomainrequest.min

约束:
1. 使用 $.ajax 发送请求,jQuery 版本需在 1.5+
2. 服务端需设置 header:header(‘Access-Control-Allow-Origin:*’);
3. 请求方式仅限:GET / POST
4. 协议仅限:HTTP / HTTPS,且必须相同
5. 仅限异步请求

客服端:

// GET
$.getJSON('http://jsonmoon.jsapp.us/').done(function(data) {
  console.log(data.name.first);
});

// POST
$.ajax({
  url: 'http://frozen-woodland-5503.herokuapp.com/cors.json',
  data: 'this is data being posted to the server',
  contentType: 'text/plain',
  type: 'POST',
  dataType: 'json'
}).done(function(data) {
  console.log(data.name.last);
});

 

服务器端:

<?php
  header('Access-Control-Allow-Origin:*');
  echo '[{"name":"123"}]';  //注意标点符号都要正确
?>

 

 

第二种跨域方法是修改header表头信息参考:《推荐看php header 跨域

nodejs 跨域表头信息修改如:

//服务器 修改如下
//客服端url接收/cors地址
app.post('/cors', function(req, res) {
 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "X-Requested-With");
 res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
 res.header("X-Powered-By", ' 3.2.1')
 res.header("Content-Type", "application/json;charset=utf-8");
 var data = {
  name: req.body.name + ' - server 3001 cors process',
  id: req.body.id + ' - server 3001 cors process'
 }
 console.log(data)
 res.send(data)
 res.end()
})

 http://mp.weixin.qq.com/s?__biz=MzAxODE2MjM1MA==&mid=2651551256&idx=1&sn=25964236012615cf673e008bfa025507&chksm=8025a1d9b75228cf18daef463a9cea1197fc8fd14a52410628d1c4a5130663dfe9d82d5d613d&scene=0#wechat_redirect

 

随身笔记

jquery ajax 跨域实例
跨域案例下载:https://sdeno.com/?p=4815   先看下jsonp原理   例子: http://www.weather.com.cn/data/cityinfo/101200101.html 天气预报提供对外接口…
扫描二维码继续阅读
2015-03-24