美文网首页
Ajax、Jsonp和 跨域

Ajax、Jsonp和 跨域

作者: 九歌丶 | 来源:发表于2019-10-10 19:23 被阅读0次

xml: Extensible Markup Language, 即 可扩展标记语言
json: JavaScript Object Notation,即 JavaScript对象简谱
ajax: Asynchronous JavaScript and XML,即 异步的JavaScript和XML, 一种前后端异步通讯技术。
jsonp: JSON with Padding, 是数据格式JSON的一种“使用模式”,利用浏览器对<script>标签没有跨域限制的“漏洞”,来达到与第三方通讯的目的。

ajax出现请求跨域错误问题,主要原因就是因为浏览器的“同源策略(协议相同 域名相同 端口相同)”。
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制,需要后端允许请求。

Ajax几种常用的api

JavaScript原生的数据通信 XHR(XMLHttpRequest):

let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
}
//get
xhr.open("get", "index.php?id=1", true);
xhr.send();
//post
xhr.open("post", "index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send('id=1');

ES6对XHR封装的原生API,Fetch:

fetch(`url`, { method: "post/get(默认get)", mode: "cors", body: "json对象或者formData对象"})
.then(res => res.json()).then(req => { todo })
.catch(err => console.log(err));

Vue的axios :

axios({
    url: '/user/12345',
    method: 'post/get(默认get)',
    data: {
      firstName: 'Fred',
      lastName: 'Flintstone'
    },
    ...
}).then(res => console.log(res))
.catch(err => console.log(err) );

Jquery的$.ajax:

$.ajax({
    url: "test.html",
    method: "post/get(默认get)",
    data:{
        firstName: 'Fred',
        lastName: 'Flintstone'
    },
    success(res){},
    error(err){}
    ...
});

相关文章

网友评论

      本文标题:Ajax、Jsonp和 跨域

      本文链接:https://www.haomeiwen.com/subject/jlwiuctx.html