Get the App
SLTechnology News&Howtos  ›  Development  › 

How to encapsulate Ajax of javascript

Shulou Source: shulou.com Published: 2022-06-02 17:32:30 09月18日 Update

This article mainly explains "how to encapsulate the Ajax of javascript". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to encapsulate the Ajax of javascript".

Basic package of ajax

Function ajax (url,fn) {

If (window.XMLHttpRequest) {var xhr = new XMLHttpRequest ();} else {var xhr = new ActiveXObject ("Microsoft.XMLHTTP");} xhr.open ("get", url,true); xhr.send (); xhr.onreadystatechange = function () {if (xhr.readyState = = 4) {if (xhr.status = = xhr.responseText; fn (data);}

Complete package of ajax

Function ajax (obj) {

/ / obj-> type url data successvar str = ""; for (var key in obj.data) {str + = key+ "=" + obj.data [key] + "&";} / / str = str.substring; str = str.replace (/ & $/, "); if (window.XMLHttpRequest) {var xhr = new XMLHttpRequest ();} else {var xhr = new ActiveXObject (" Microsoft.XMLHTTP ") } if (obj.type.toUpperCase () = = "GET") {if (obj.data) {var url = obj.url + "?" + str;} else {var url = obj.url;} xhr.open ("get", url,true); xhr.send ();} if (obj.type.toUpperCase () = = "POST") {xhr.open ("post", obj.url,true) Xhr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); xhr.send (str);} Thank you for reading, the above is the content of "how to encapsulate the Ajax of javascript". After the study of this article, I believe you have a deeper understanding of how to encapsulate the Ajax of javascript, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Encapsulation learning content that is ideas situations articles more knowledge knowledge points articles follow questions practice push research verification Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Microsoft Redmi Apple OPPO Reno