Several methods for implementing native ajax using javascript

Source: Internet
Author: User

Since JavaScript has various frameworks, such as jquery, using ajax has become quite simple. However, for simplicity, you may not need to load a huge js plug-in such as jquery in the project. But what should I do if I want to use ajax? We will share with you several ways to use javascript to implement native ajax.

Before implementing ajax, you must create an XMLHttpRequest object. If you cannot create a browser for this object, you need to create ActiveXObject as follows:

var xmlHttp;function createxmlHttpRequest(){if(window.ActiveXObject){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}else if(window.XMLHttpRequest)xmlHttp=new XMLHttpRequest();}

(1) Use the xmlHttp created above to implement the simplest ajax get request:

Function doGet (url) {// note that it is best to use encodeURI to process parameter values to prevent garbled code createxmlHttpRequest (); xmlHttp. open ("GET", url); xmlHttp. send (null); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {alert ('success');} else {alert ('fail ');}}}

(2) Use the xmlHttp created above to implement the simplest ajax post request:

Function doPost (url, data) {// note that it is best to use encodeURI to process parameter values to prevent garbled code createxmlHttpRequest (); xmlHttp. open ("POST", url); xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (data); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {alert ('success');} else {alert ('fail ');}}}

(3) Next we will share an encapsulation of the $. ajax method that simulates jquery from the Internet:

Var createAjax = function () {var xhr = null; try {// xhr = new ActiveXObject ("microsoft. xmlhttp ");} catch (e1) {try {// non-IE browser xhr = new XMLHttpRequest ();} catch (e2) {window. alert ("your browser does not support ajax. Please change it! ") ;}} Return xhr ;}; var ajax = function (conf) {var type = conf. type; // type parameter; optional; var url = conf. url; // url parameter. var data = conf is required. data; // optional data parameter. var dataType = conf is required only for post requests. dataType; // optional var success = conf. success; // callback function optional if (type = null) {// type parameter optional, default: get type = "get";} if (dataType = null) {// optional; default value: text dataType = "text";} var xhr = createAjax (); xhr. open (type, url, true); if (type = "GET" | type = "Get") {xhr. send (null);} else if (type = "POST" | type = "post") {xhr. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); xhr. send (data);} xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {if (dataType = "text" | dataType = "TEXT") {if (success! = Null) {// common text success (xhr. responseText) ;}} else if (dataType = "xml" | dataType = "XML") {if (success! = Null) {// receive the xml document success (xhr. responseXML) ;}} else if (dataType = "json" | dataType = "JSON") {if (success! = Null) {// convert the json string to the js object success (eval ("(" + xhr. responseText + ")"));}}}};};

This method is also very easy to use. It is the same as jquery's $. ajax method, but there are not so many parameters. It simply implements some basic ajax functions. The usage is as follows:

Ajax ({type: "post", // post or get, not required url: "test. jsp ", // required data:" name = dipoo & info = good ", // non-required ype:" json ", // text/xml/json, success: function (data) {// callback function, not alert (data. name );}});
Articles you may be interested in
  • Summary of the string truncation function implemented by javascript (including introduction to the use of Js to intercept Chinese characters)
  • JQuery implements several effects of gradient switching of images
  • How to integer JavaScript Decimals
  • How to refresh a page using javascript
  • Js: Click enter and move the cursor to the next input box.
  • Several methods for generating random numbers using PHP
  • JavaScript retrieves the current date and time and displays the day of the week at the same time
  • Php output yesterday, today, tomorrow is the day of the week

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.