ajax通信过程及限制,前端通信

同源策略及限制

1、先来说说什么是源

• 源(origin)就是协议、域名和端口号。

以上url中的源就是:http://www.company.com:80

若地址里面的协议、域名和端口号均相同则属于同源。

以下是相对于 http://www.a.com/test/index.html 的同源检测

• http://www.a.com/dir/page.html ----成功

• http://www.child.a.com/test/index.html ----失败,域名不同

• https://www.a.com/test/index.html ----失败,协议不同

• http://www.a.com:8080/test/index.html ----失败,端口号不同

2.什么是同源策略?

同源策略是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源。所以a.com下的js脚本采用ajax读取b.com里面的文件数据是会报错的。

• 不受同源策略限制的:

1、页面中的链接,重定向以及表单提交是不会受到同源策略限制的。

2、跨域资源的引入是可以的。但是js不能读写加载的内容。如嵌入到页面中的,,,等。

前后端如何通信

Ajax 支持同源通信

WebSocket 不受同源策略影响

CORS 既支持同源通信也支持跨域通信

如何创建ajax

XMLHttpResquest 对象的工作流程

兼容性处理

事件的触发条件

事件的触发顺序

util.json = function (options) {

var opt = {

url: '',

type: 'get',

data: {},

success: function () {},

error: function () {},

};

util.extend(opt, options);

if (opt.url) {

var xhr = XMLHttpRequest

? new XMLHttpRequest()

: new ActiveXObject('Microsoft.XMLHTTP');

var data = opt.data,

url = opt.url,

type = opt.type.toUpperCase(),

dataArr = [];

for (var k in data) {

dataArr.push(k + '=' + data[k]);

}

if (type === 'GET') {

url = url + '?' + dataArr.join('&');

xhr.open(type, url.replace(/\?$/g, ''), true);

xhr.send();

}

if (type === 'POST') {

xhr.open(type, url, true);

xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

xhr.send(dataArr.join('&'));

}

xhr.onload = function () {

if (xhr.status === 200 || xhr.status === 304) {

var res;

if (opt.success && opt.success instanceof Function) {

res = xhr.responseText;

if (typeof res === 'string') {

res = JSON.parse(res);

opt.success.call(xhr, res);

}

}

} else {

if (opt.error && opt.error instanceof Function) {

opt.error.call(xhr, res);

}

}

};

}

};

跨域通信的几种方式

JSONP

util.jsonp = function (url, onsuccess, onerror, charset) {

var callbackName = util.getName('tt_player');

window[callbackName] = function () {

if (onsuccess && util.isFunction(onsuccess)) {

onsuccess(arguments[0]);

}

};

var script = util.createScript(url + '&callback=' + callbackName, charset);

script.onload = script.onreadystatechange = function () {

if (!script.readyState || /loaded|complete/.test(script.readyState)) {

script.onload = script.onreadystatechange = null;

// 移除该script的 DOM 对象

if (script.parentNode) {

script.parentNode.removeChild(script);

}

// 删除函数或变量

window[callbackName] = null;

}

};

script.onerror = function () {

if (onerror && util.isFunction(onerror)) {

onerror();

}

};

document.getElementsByTagName('head')[0].appendChild(script);

};

Hash

// 在A中伪代码如下:

var B = document.getElementsByTagName('iframe');

B.src = B.src + '#' + 'data';

// 在B中的伪代码如下

window.onhashchange = function () {

var data = window.location.hash;

};

postMessage

// 窗口A(http:A.com)向跨域的窗口B(http:B.com)发送信息

Bwindow.postMessage('data', 'http://B.com');

// 在窗口B中监听

Awindow.addEventListener('message', function (event) {

console.log(event.origin);

console.log(event.source);

console.log(event.data);

}, false);

WebSocket

var ws = new WebSocket('wss://echo.websocket.org');

ws.onopen = function (evt) {

console.log('Connection open ...');

ws.send('Hello WebSockets!');

};

ws.onmessage = function (evt) {

console.log('Received Message: ', evt.data);

ws.close();

};

ws.onclose = function (evt) {

console.log('Connection closed.');

};

CORS

// CORS【参考资料】http://www.ruanyifeng.com/blog/2016/04/cors.html

// url(必选),options(可选)

fetch('/some/url/', {

method: 'get',

}).then(function (response) {

}).catch(function (err) {

// 出错了,等价于 then 的第二个参数,但这样更好用更直观

});

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值