ajax get and post combo package

<script>

= function the document.onclick () {
Ajax ({
// type: "GET", // transmission mode, alternatively, the default GET
URL: "HTTP: //localhost/1908/ajax/data/data.php", / / to address request Required
success: function (res) {// function after a successful request, required
the console.log (RES)
},
// data: {// the data to be transmitted, alternatively, the default is not hair
// User: "ADMIN",
// Pass: 13,123,121,123
//},
// error: function (RES) {// function after the request fails, alternatively, the default is not processed
// the console.log (RES)
/ /},
// timeout: 10 // request timeout, optional, default 2000
})
}

function ajax(options){
// 1.处理默认参数
var {type,url,success,error,data,timeout} = options;
type = type || "get";
data = data || {};
timeout = timeout || 2000;

// 2. Parse the data to be transmitted
var STR = "";
for (var Data in I) {
STR $ `+ = {I} = $ {Data [I]} &`;
}

// The way, the decision whether to process URL
IF (type == "GET") {
var new new D = a Date ();
"?" URL URL = + + + STR "__qft =" + d.getTime ();
}

4. // Open Ajax
var = new new XHR the XMLHttpRequest ();
// Note: open in a manner
xhr.open (type, URL, to true);
xhr.onreadystatechange = function () {
IF (xhr.readyState. 4 && == xhr.status == 200) {
// Define 5. executed successfully, first determine whether the incoming
success && success (xhr.responseText);
then // successful, there should be a failure
error = null;
} the else iF (xhr.readyState ! == 4 && xhr.status = 200) {
// Define 6. fails, first determine whether the incoming
error && error (xhr.status);
then // failure, there should be no success
success = null;
// and failure should not perform multiple
error = null;
}
}

// 7. If the request times out, fails
the setTimeout (() => {
error && error ( "timeout");
after // failure, there should be no success
Success = null;
}, timeout);

// 8. Finally, according to type of embodiment, the decision to send contents and send the format
IF (type == "POST") {
xhr.setRequestHeader ( "the Content-type", "file application / X-WWW-form-urlencoded");
xhr.send (STR)
} the else {
xhr.send ()
}
}

</script>

Guess you like

Origin www.cnblogs.com/shun1015/p/11496230.html