JavaScript natively encapsulates an Ajax data request function

Initiate network request body part

 function urlReques(dict){ /* 封装一个数据请求函数*/ var xhr = new XMLHttpRequest(); var qs = resolveData(dict.data); if(dict.method.toUpperCase() === "GET"){ xhr.open(dict.method,dict.url + '?' + qs); xhr.send() }else if(dict.method.toUpperCase() === "POST"){ xhr.open(dict.method,dict.url); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(qs); } // 监听请求状态xhr.onreadystatechange = function(){ console.log(xhr.status) if(xhr.readyState === 4 && xhr.status === 200){ var result = JSON.parse(xhr.responseText); dict.success(result); } } }

If a 415 error occurs when using a post request, it may be a problem with the request header. The following modifications may solve the problem

Will

 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(qs);

change into

 xhr.setRequestHeader('Content-Type','application/json; charset=utf-8'); xhr.send(JSON.stringify(dict.data));

Convert the data object to the format of the query string

That is, a format similar to name=Asnull&no=1

 function resolveData(data){ /* 将对象转换为查询字符串格式*/ var arr = [] for(var key in data){ arr.push(key + "=" + data[key]) } return arr.join("&") }

Call the function to initiate a network request

 urlReques({ method:'POST', url:'https://blog.lipux.cn/api', data:{ name:'Asnull', no:1 }, success:function(res){ // 请求成功之后的回调函数res为返回的结果console.log(res) } })

method is the request method is divided into post and get
url is the request interface
data is the parameter to be submitted, written in the form of js object
success is the callback function after the request is successful

This article is reproduced from: https://blog.lipux.cn/archives/332.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment