fetch ajax cros,JavaScript -AJAX/FETCH GET/POST及跨域方法

xhr 原生方法请求

var apiURL = 'https://api.github.com/repos/vuejs/vue/commits?per_page=3&sha=';

var currentBranch='master';

var commits= null;

function fetchData() {

var xhr = new XMLHttpRequest()

var self = this

xhr.open('GET', apiURL + self.currentBranch)

xhr.onload = function () {

self.commits = JSON.parse(xhr.responseText)

console.log(self.commits[0].html_url)

}

xhr.send()

}

function fetchDataPost(){

// unload 时尽量使用同步 AJAX 请求

xhr("POST",{

url: location.href,

sync: true,

handleAs: "text",

content:{

param1:1

},

load:function(result){

console.log(result);

}

});

};

window fetch 方法

async function Fetch({url, data, method, config}) {

method = method.toUpperCase();

//window fetch方法

if (window.fetch) {

let requestConfig = {

credentials: 'include',

method: method,

headers: {

'Accept': 'application/json',

'Content-Type': 'application/json'

},

mode: "cors",

cache: "force-cache"

};

function assignConfig(targetConfig, sourceConfig) {

if (sourceConfig) {

Object.keys(sourceConfig).forEach(key => {

if (sourceConfig[key]) {

if (typeof sourceConfig[key] !== "object") {

if (sourceConfig[key]) Object.assign(targetConfig, sourceConfig)

} else {

assignConfig(targetConfig[key], sourceConfig[key])

}

}

})

}

}

assignConfig(requestConfig, config);

if (method === 'POST') {

Object.defineProperty(requestConfig, 'body', {

value: JSON.stringify(data)

})

}

try {

var response = await fetch(url, requestConfig);

var responseJson = await response.json();

} catch (error) {

throw new Error(error)

}

return responseJson

} else {

let requestObj;

if (window.XMLHttpRequest) {

requestObj = new XMLHttpRequest();

} else {

requestObj = new ActiveXObject;

}

let sendData = '';

if (method === 'POST') {

sendData = JSON.stringify(data);

}

requestObj.open(method, url, true);

if (config.headers) Object.keys(config.headers).forEach(key => {

if (config.headers[key]) requestObj.setRequestHeader(key, config.headers[key])

});

requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

requestObj.send(sendData);

requestObj.onreadystatechange = () => {

if (requestObj.readyState === 4) {

if (requestObj.status === 200) {

let obj = requestObj.response;

if (typeof obj !== 'object') {

obj = JSON.parse(obj);

}

return obj

} else {

throw new Error(requestObj)

}

}

}

}

}

var baseUrl = "http://localhost:5000/api/";

var loginUrl = "authentication/Login";

var config = {

headers: {

Authorization: "Basic dXNlcm5hbWU6cGFzc3dvcmQ="

}

};

Fetch({

url: baseUrl + loginUrl,

method: "post",

data: {"Name": "wwmin", "password": "1"},

config

}).then(res => console.log(res));

关于跨域

//1.同源请求

$("#submit").click(function(){

var data={

name:$("name").val(),

id:$("#id").val();

};

$.ajax({

type:"POST",

data:data,

url:"http://localhost:3000/ajax/deal",

dataType:"json",

cache:false,

timeout:5000,

success:function(data){

console.log(data);

},

error:function(jqXHR,textStatus,errorThrown){

console.log("error"+textStatus+" "+errorThrown);

}

});

});

//node 服务器端3000 对应的处理函数为:

pp.post('/ajax/deal',function(req,res){

console.log("server accept:",req.body.name,req.body.id)

var data={

name:req.body.name+'-server 3000 process',

id:req.body.id+'-server 3000 process'

};

res.send(data);

res.end();

})

利用JSONP实现跨域调用

//JSONP 是 JSON 的一种使用模式,可以解决主流浏览器的跨域数据访问问题。

// 其原理是根据 XmlHttpRequest 对象受到同源策略的影响,而 标签元素却不受同源策略影响,

// 可以加载跨域服务器上的脚本,网页可以从其他来源动态产生 JSON 资料。用 JSONP 获取的不是 JSON 数据,

// 而是可以直接运行的 JavaScript 语句。

//2.使用 jQuery 集成的 $.ajax 实现 JSONP 跨域调用

//回调函数

function jsonpCallback(data){

console.log("jsonpCallback:"+data.name)

}

$("#submit").click(function(){

var data={

name:$("#name").val(),

id:$("#id").val();

};

$.ajax({

url:'http://localhost:3001/ajax/deal',

data:data,

dataType:"jsonp",

cache:false,

timeout:5000,

//jsonp字段含义为服务器通过什么字段获取回调函数的名称

jsonp:'callback',

//声明本地回调函数的名称,jquery默认随机生成一个函数名称

jsonpCallback:'jsonpCallback',

success:function(data){

console.log("ajax success callback:"+data.name)

},

error:function(jqXHR,textStatus,errorThrown){

console.log(textStatus+''+errorThrown);

}

});

});

//服务器3001上对应的处理函数为

app.get('/ajax/deal',function(req,res){

console.log("serer accept:");

var data="{"+"name:"+req.query.name+"-server 3001 process',"+"id:'"+req.query.id+"-server 3001 process'"+"}";

var callback=req.query.callback;

var jsonp=callback+'('+data+')';

console.log(jsonp);

res.send(jsonp);

res.end();

})

//请求头第一行为

GET /ajax/deal?callback=jsonpCallback&name=chiaki&id=3001&_=1473164876032 HTTP/1.1

//使用script标签原生实现JSONP

function jsonpCallback(data){

console.log("jsonpCallback:"+data.name)

}

//服务器 3000请求页面还包含一个 script 标签:

//服务器 3001上对应的处理函数:

app.get('/jsonServerResponse', function(req, res) {

var cb = req.query.jsonp

console.log(cb)

var data = 'var data = {' + 'name: $("#name").val() + " - server 3001 jsonp process",' + 'id: $("#id").val() + " - server 3001 jsonp process"' + '};'

var debug = 'console.log(data);'

var callback = '$("#submit").click(function() {' + data + cb + '(data);' + debug + '});'

res.send(callback)

res.end()

})

使用 CORS(跨域资源共享) 实现跨域调用

//CORS 的实现

//服务器 3000 上的请求页面 JavaScript 不变 (参考上面的同域请求)

//服务器 3001上对应的处理函数:

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()

})

// CORS 中属性的分析

//1.Access-Control-Allow-Origin

The origin parameter specifies a URI that may access the resource. The browser must enforce this. For requests without credentials, the server may specify “*” as a wildcard, thereby allowing any origin to access the resource.

//2.Access-Control-Allow-Methods

Specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above.

//3.Access-Control-Allow-Headers

Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.

// CORS 与 JSONP 的对比

//1.CORS 除了 GET 方法外,也支持其它的 HTTP 请求方法如 POST、 PUT 等。

//2.CORS 可以使用 XmlHttpRequest 进行传输,所以它的错误处理方式比 JSONP 好。

//3.JSONP 可以在不支持 CORS 的老旧浏览器上运作。

//一些其它的跨域调用方式

//1.window.name

//2.window.postMessage()

//参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值