XMLHttpRequest发送请求示例

通常get请求可以直接在浏览器地址栏输入,查看响应数据;对于post请求,可以直接粘贴下列代码在浏览器控制台console中执行,然后根据实际需要发送请求即可。
减少使用postman等客户端工具的麻烦。

该博文没有理解学习的价值,方便复制代码使用而已

代码
var XMLHttpReq;
function createXMLHttpRequest() {
  try {
    XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
  } catch(e) {
    try {
      XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
      XMLHttpReq = new XMLHttpRequest();
    }
  }
}
function sendAjaxRequest(url, data) {
  createXMLHttpRequest();
  XMLHttpReq.open("post", url, true);
  XMLHttpReq.onreadystatechange = processResponse; 
  XMLHttpReq.send(data);
}
function processResponse() {
  if (XMLHttpReq.readyState == 4) {
    if (XMLHttpReq.status == 200) {
      var text = XMLHttpReq.responseText;
      alert(text)
    }
  }
}
使用
var data = 'name=Jay&age=23';
var url = 'http://...';
sendAjaxRequest(url, data);

至此,结束。

猜你喜欢

转载自blog.csdn.net/Jacoh/article/details/84331281
今日推荐