发送GET请求html
var xhr = new XMLHttpRequest(); xhr.open('GET',url);//url为请求地址 xhr.responseType = 'json'; xhr.onload = function () { // 请求结束后,在此处写处理代码 }; xhr.onerror = function(){//请求错误 console.log('xhr error'); } xhr.send();
发送POST请求json
var xhr = new XMLHttpRequest(); xhr.open("POST", url, true); //发送合适的请求头信息 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() {//Call a function when the state changes. if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { // 请求结束后,在此处写处理代码 } } xhr.send("foo=bar&lorem=ipsum");
//fetch()返回一个promise,它将解析从服务器发回的响应。咱们使用then()来运行一些后续代码 fetch(url).then(function(response){ //处理text/html响应 至关于 xhr.responseType = 'json'; //return response.text(); //json响应 return response.json(); }).then(function(data){ //至关于xhr.onload =function(){} console.log(data); }).catch(function(e){//至关于xhr.onerror =function(){} console.log('error' + e); });
获取头信息:promise
fetch(url).then((response)=>{ console.log(response.status); console.log(response.statusText); console.log(response.headers.get('Content-Type')); console.log(response.headers.get('Date')); return response.json(); }).then(function(data){ console.log(data); }) .catch(function(e){ console.log('error' + e); });
设置头信息浏览器
fetch(url,{ headers:{ 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then((response)=>{ return response.json(); }).then(function(data){ console.log(data); }) .catch(function(e){ console.log('error' + e); });
提交表单服务器
fetch(url,{ method: 'post', body: new FormData(document.getElementById('form')) }).then((response)=>{ return response.json(); }).then(function(data){ console.log(data); }) .catch(function(e){ console.log('error' + e); });
提交json数据app
fetch(url,{ method: 'post', body: JSON.stringify({ username: document.getElementById('username').value, password: document.getElementById('password').value }) }).then(function(data){ console.log(data); }) .catch(function(e){ console.log('error' + e); });
本文摘抄于
XMLHttpRequest异步
Fetchpost