0 1059

ReferenceError: XMLHttpRequest is not defined

fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源,主流浏览器基本都支持,IE除外。

下面我就来介绍下怎么用fetch 来代替 jQuery的post。

/*

*@parm url 请求服务器地址

*@parm data 数组

*@parm 请求成成返回的函数

*/

function erlyun_ajax(url,data,messagejsfun1) {


fetch(url, {

body: JSON.stringify(data), // must match 'Content-Type' header

cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached

credentials: "same-origin", // include, same-origin, *omit

headers: {

"user-agent": "Mozilla/4.0 MDN Example",

"content-type": "application/json"

},

method: "POST", // *GET, POST, PUT, DELETE, etc.

mode: "cors", // no-cors, cors, *same-origin

redirect: "follow", // manual, *follow, error

referrer: "no-referrer" // *client, no-referrer

}).then(response => response.json()).then(function(myJson) {

console.log(myJson);

if(typeof(messagejsfun1) == 'function'){

          messagejsfun1(myJson);

          }

});

    

}

下面是可直接复制的代码

function erlyun_ajax(url,data,messagejsfun1) {
	
	fetch(url, {
	body: JSON.stringify(data), // must match 'Content-Type' header
	cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
	credentials: "same-origin", // include, same-origin, *omit
	headers: {
		"user-agent": "Mozilla/4.0 MDN Example",
		"content-type": "application/json"
	},
	method: "POST", // *GET, POST, PUT, DELETE, etc.
	mode: "cors", // no-cors, cors, *same-origin
	redirect: "follow", // manual, *follow, error
	referrer: "no-referrer" // *client, no-referrer
	}).then(response => response.json()).then(function(myJson) {
		console.log(myJson);
		if(typeof(messagejsfun1) == 'function'){
		          messagejsfun1(myJson);
	          }
	});
    
}

调用方法

var get_url = 'https://yuanmouren.erlyun.com/p?do=add1&cid=6';//最好是https的地址

var paramdata = {'ubid':ubid};

erlyun_ajax(get_url,paramdata,function(data){

  //@请求成功的逻辑

});

[分类]
[来源] http://erlangyun.com/p/id/161.html
[声明] 本站资源来自用户分享,如损害你的权益请联系客服QQ:120074275给予处理。