js 兼容ie6/7/8跨域 跨域
一般涉及到跨域时,我们都会使用jquery里面ajax的jsonp,但是遇到ie浏览器就不兼容了。这里推荐使用reqwest.js,对浏览器的兼容性很好支持xmlHttpRequest, JSONP, CORS, 和 CommonJS。
同时也能在node.j后台和前端上使用
IE6+
Chrome 1+
Safari 3+
Firefox 1+
Opera
具体没测试这么多浏览器,但至少满足了ie8,跨域以及各种常用功能。
跨域
使用的是jsonp,兼容比较老的浏览器如,ie6/7
//客服端 reqwest({ url: 'https://sdeno.com/a.php' , method: 'get' //jsonp用的就是get方式跨域的,改成post也会默认是get ,type: 'jsonp' , jsonpCallbackName: 'ni' , success: function (resp) { document.title=JSON.stringify(resp) } })
//服务器端 a.php <?php $data='[{name:"chenge"},{age:24}]'; $str='ni('.$data.')'; echo $str; ?>
以下使用CORS方法跨域,支持跨域携带cookies,支持全部方式请求,IE8以上浏览器使用new XDomainRequest(),其他浏览器使用new XMLHttpRequest()
//客户端 reqwest({ url: 'http://45.32.197.68/a.php' //可以是接收数据的地址,也可以是要发送给服务器数据的地址 , type: 'json' , method: 'post' , contentType: 'application/json' , crossOrigin: true , withCredentials: true //cookies跨域要设置true,但是Access-Control-Allow-Origin:的值就不能是*,不然会报错。 , error: function (err) { } , success: function (resp) { qwery('#content').html(resp.content) } })
客户端使用cors来实现跨域,服务器也要设置。
<?php if(isset($_SERVER["HTTP_ORIGIN"])) { header('Access-Control-Allow-Origin:'.$_SERVER["HTTP_ORIGIN"]); } header('Access-Control-Allow-Methods:OPTIONS, GET, POST'); header('Access-Control-Allow-Headers:x-requested-with'); header('Access-Control-Max-Age:86400'); header('Access-Control-Allow-Origin:'.$_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Credentials:true'); header('Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers:x-requested-with,content-type'); header('Access-Control-Allow-Headers:Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'); $data='[{"name":"chenge"},{"age":"24"}]'; echo $data; ?>
关于:cors跨域请求的服务器配置参考地址:http://www.jianshu.com/p/552daaf2869c
post/get方式提交数据给服务器
//post提交数据 reqwest({ url: 'path/to/html' //服务器接收数据地址 , type: 'json' //将数据以json格式发给服务器 , method: 'post' , data: { foo: 'bar', baz: 100 } //要发给服务器的数据 , success: function (resp) { qwery('#content').html(resp) } }) //get提交数据 reqwest({ url: 'path/to/html' , type: 'json' , method: 'get' , data: [ { name: 'foo', value: 'bar' }, { name: 'baz', value: 100 } ] //http://localhost:3001/xxx1?foo=bar&baz=100 //或者{ foo: 'bar', baz: 100 } , success: function (resp) { qwery('#content').html(resp) } })
回调
reqwest.({})
.then(function (resp) { //成功回调
qwery('#content').html(resp.content)
})
.fail(function (err, msg) { //失败回调
qwery('#errors').html(msg)
})
.always(function (resp) { //总是回调
qwery('#hide-this').hide()
})
对IE6/7的兼容
<script> (function () { if (!window.JSON) { document.write('<scr' + 'ipt src="http://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"><\/scr' + 'ipt>') } }()); </script>