ajax的get请求与post请求
程序员文章站
2022-04-15 18:06:56
...
Ajax 技术核心是JavaScript对象XMLHttpRequest(简称 XHR), 它是一种支持异步请求数据的技术.
与服务器进行数据交换,实现同步或异步的刷新.
ajax.post.js
const Ajax = (function () {
// {uname:123,upwd:123};
// uname=123&upwd=123&
function getPrams(obj) {
var str = "";
for (var key in obj) {
str += key + '=' + obj[key] + "&";
}
return str;
}
function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest()
}
return new ActiveXObject('Msxml2.XMLHTTP');
}
return function (url, data, callback) {
var xhr = createXHR();
xhr.open('post', url, true);
//告诉服务器,浏览器这边发送过去的内容是 仿form表格格式的数据
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//可以要求服务器返送 json过来
xhr.responseType = "json";
xhr.send(getPrams(data));
xhr.onreadystatechange = function () {
if (xhr.status == 200) {
if (xhr.readyState == 4) {
if (typeof (callback) == "function") {
callback(xhr.response);
}
}
}
}
}
})()
ajax.get.js
const Ajax = (function () {
// {uname:abc123,upwd:123};
// uname=abc123&upwd=123
function getParams(obj) {
var str = "";
for (key in obj) {
str += key + "=" + obj[key] + "&";
}
return str;
}
//1.创建ajax核心对象
function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
return new ActiveXObject("Msxml2.XMLHTTP");
}
//2.创建ajax
return function (url, data, callback) {
var xhr = createXHR();
xhr.open("get", url + "?" + getParams(data), true); //异步
xhr.send(null);
//异步如何拿到数据?
xhr.onreadystatechange = function () {
if (xhr.status == 200) {
if (xhr.readyState == 4) {
if (typeof (callback) == "function") {
callback(xhr.response);
}
}
}
}
}
})();