原生ajax如何传值json数据
GET和Delete方法
var xhr = new XMLHttpRequest()
xhr.open(httpMethod, url, true)
//xhr.withCredentials = true
xhr.send()
xhr.onreadystatechange = () =>{
if((xhr.readyState == XMLHttpRequest.DONE) && (xhr.status == 200)){
callback(JSON.parse(xhr.responseText))
}
}
POST,PUT等方法
var xhr = new XMLHttpRequest()
xhr.open(httpMethod, url, true)
xhr.withCredentials = true
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = () =>{
if ((xhr.readyState == XMLHttpRequest.DONE) && (xhr.status == 200)) {
callback(JSON.parse(xhr.responseText))
}
}
xhr.send(JSON.stringify(data))
简单说:
按json上传的标准,body放json字符串,header加上Content-Type: application/json
。
通常大部分库,直接把一个object给body,就是这样处理的。
等等,我找找看。
这是我使用的vue-resource的header写法。
https://github.com/vuejs/vue-...