原生的js实现ajax请求

xiaoxiao2021-02-28  101

1、get和post请求

function getXMLHttpRequest() { var xhr; if(window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }else if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else { xhr = null; } return xhr; } /* *data = 'id=1122&name="liyongfen"' */ function ajax(method,url,data,callback) { var xhr = getXMLHttpRequest(); if(method == 'post' || method == 'POST'){ xhr.open(method,url,true); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.send(data); }else if(method == 'get' || method == 'GET'){ xhr.open(method,url + '?' + data,true); xhr.send(); } xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { callback(xhr.responseText); } } }

注释:get请求与post的区别,get将参数放入url中发送。post需要设置请求头部,将发送的数据data放入xhr.send(data);中。

转载请注明原文地址: https://www.6miu.com/read-27858.html

最新回复(0)