Describes how to implement AJAX processing in jQuery using native JavaScript, jqueryajax

Source: Internet
Author: User

Describes how to implement AJAX processing in jQuery using native JavaScript, jqueryajax

In this article, I use Node. js as the backend. That's right, so we can use the full-stack (browser and server) JS. Node. js is very concise. I encourage you to download the demo on Github and pay attention to this project. The following is the server code:

// app.jsvar app = http.createServer(function(req, res){  if(req.url.indexOf("/scripts/") >= 0){    render(req.url.slice(1), "application/javascript", httpHandler);  } else if(req.headers['x-requested-with'] === 'XMLHttpRequest'){    // Send Ajax response  } else{    render('views/index.html', 'text/html', httpHandler);  }}

The code snippet detects the request URL and determines the content returned by the app. If the request comes from the scripts directory, the server returns the corresponding file whose content type is application/javascript. If x-requested-with in the request header is set to XMLHttpRequest, the request is an Ajax request and the corresponding data is returned. In addition to the preceding two cases, the server returns views/index.html.

Next I will show you the comments for processing Ajax requests in a code segment for further explanation. On the Node. js side, I have processed the physical activity of render and httpHandler:

// app.jsfunction render(path, contentType, fn) {  fs.readFile(__dirname + '/' + path, 'utf-8', function (err, str) {    fn(err, str, contentType);  });}var httpHandler = function (err, str, contentType) {  if (err) {    res.writeHead(500, {'Content-Type': 'text/plain'});    res.end('An error has occured: ' + err.message);  } else {    res.writeHead(200, {'Content-Type': contentType});    res.end(str);  }};


The render function asynchronously reads the content of the requested file. This function transfers a reference to the httpHandler used as the callback function.
The httpHandler function checks whether the error object exists. (For example, if the requested file cannot be opened, the object will exist ). In addition, specifying the type is a good practice. The file content returned by the server will have the appropriate HTTP status code and content type ).

Test API
Let's write some unit tests for the back-end APIs to ensure they can run correctly. For such tests, I will ask supertest and mocha for help.

// test/app.request.jsit("responds with html", function(done){  request(app)    .get("/")    .expect("Content-Type", /html/)    .expect(200, done);});it('responds with javascript', function (done) {request(app)  .get('/scripts/index.js')  .expect('Content-Type', /javascript/)  .expect(200, done);});it('responds with json', function (done) {request(app)  .get('/')  .set('X-Requested-With', 'XMLHttpRequest')  .expect('Content-Type', /json/)  .expect(200, done);});

These tests ensure that our app can return the correct content type and HTTP status code for different requests ). Once you install these dependencies, you can run these tests using the command npm test.

Interface
Now, let's take a look at the HTML code of the user interface:

// views/index.html

The preceding HTML code looks simple. Yes, as you can see, all the exciting things happen in JavaScript.

Onreadystate vs onload
If you have read any authoritative book about Ajax, you may find that onreadystate is everywhere in the book. This callback function needs to be completed through nested ifs or multiple case statements, which makes it hard to remember. Let's review the onreadystate and onload events.

(Function () {var retrieve = document. getElementById ('retrieve '), results = document. getElementById ('result'), toReadyStateDescription = function (state) {switch (state) {case 0: return 'unsent'; case 1: return 'opened'; case 2: return 'headers _ received'; case 3: return 'loading '; case 4: return 'done'; default: return '';}}; retrieve. addEventListener ('click', function (e) {var oReq = new XMLHt TpRequest (); oReq. onload = function () {console. log ('Inside the onload event');}; oReq. onreadystatechange = function () {console. log ('Inside the onreadystatechange ev! [Enter the image description here] [1] ent with readyState: '+ toReadyStateDescription (oReq. readyState) ;}; oReq. open ('get', e.tar GET. dataset. url, true); oReq. send ();});}());

The above code will output the following statement on the console:

The onreadystatechange event can be triggered in any process of the request. Such as before and at the end of each request. However, according to the document, the onload event will only be triggered after the request is successful. Because the onload event is a common API, you can master it in a short time. Onreadystatechange event can be used as a backup (the original article is backwards compatible backward compatible ?) Solution. Onload events should be your first choice. In addition, the onload event is similar to the success callback function of jQuery, isn't it?

### Set the Request Header
JQuery sets the Request Header for you in private, so the backend can detect that this is an Ajax request. In general, the backend does not care where the GET request comes from, as long as it returns the correct response. This is useful when you use the same web API to return Ajax or HTML. Let's take a look at how to set the request header through Native JavaScript:

var oReq = new XMLHttpRequest();oReq.open('GET', e.target.dataset.url, true);oReq.setRequestHeader('X-Requested-With', 'XMLHttpRequest');oReq.send();

At the same time, we perform a test in Node. js:


 

if (req.headers['x-requested-with'] === 'XMLHttpRequest') {  res.writeHead(200, {'Content-Type': 'application/json'});  res.end(JSON.stringify({message: 'Hello World!'}));}

As you can see, native Ajax is a flexible and modern front-end API. You can use the request header to do many things, one of which is version control. For example, I want a web API to support multiple versions. But I don't want to use URLs. Instead, I set the request header so that the client can select the desired version. Therefore, we can set the request header as follows:

oReq.setRequestHeader('x-vanillaAjaxWithoutjQuery-version', '1.0');

Then, write the corresponding code on the backend:


 

if (req.headers['x-requested-with'] === 'XMLHttpRequest' &&  req.headers['x-vanillaajaxwithoutjquery-version'] === '1.0') {  // Send Ajax response}

We can use Node. js to detect the headers objects we provide. The only thing to note is: Read them with lower-case letters.

Response type
You may want to know why responseText returns a string instead of a common JSON (Plain Old JSON) that can be operated by us ). It turns out that I didn't set the appropriate responseType attribute. This Ajax attribute will tell the data type that the front-end API expects the server to return. Therefore, we should make good use of it:

var oReq = new XMLHttpRequest();oReq.onload = function (e) {  results.innerHTML = e.target.response.message;};oReq.open('GET', e.target.dataset.url, true);oReq.responseType = 'json';oReq.send();

Wow, so we don't have to parse the returned plain text into JSON. We can tell the API the type of data we expect to receive. This feature is supported by almost all the latest mainstream browsers. Of course, jQuery will automatically convert us to the appropriate type. However, the current native JavaScript has a convenient way to complete the same event. Native Ajax already supports many other response types, such as XML.

Unfortunately, the development team has not yet supported xhr. responseType = 'json' until IE11. This feature is currently supported in Microsoft Edge. However, this Bug has been raised for almost two years. I firmly believe that the Microsoft team has been striving to improve browsers. Let's look forward to Microsoft Edge and aka Project Spartan's original commitment.
Of course, you can solve this IE problem:

oReq.onload = function (e) {  var xhr = e.target;  if (xhr.responseType === 'json') {    results.innerHTML = xhr.response.message;  } else {    results.innerHTML = JSON.parse(xhr.responseText).message;  }};

Avoid caching
The browser features that cache Ajax requests are almost forgotten. For example, IE is like this by default. I also worried for several hours that caused my Ajax not to be executed. Fortunately, jQuery clears the browser cache by default. Of course, you can achieve this in pure Ajax, and it is quite simple:

var bustCache = '?' + new Date().getTime();oReq.open('GET', e.target.dataset.url + bustCache, true);

You can see that jQuery appends a timestamp after each request (GET) as the query string. To some extent, this makes the request unique and avoids browser caching. Every time you trigger an HTTP Ajax request, you can see a request similar to the following:

OK! This is nothing dramatic.

Summary
I hope you will like this article about native Ajax. In the past, Ajax was seen as a terrible monster. In fact, we have covered all the basic knowledge of native Ajax.

Finally, I will leave you with a simple method to call Ajax:

var oReq = new XMLHttpRequest();oReq.onload = function (e) {  results.innerHTML = e.target.response.message;};oReq.open('GET', e.target.dataset.url + '?' + new Date().getTime(), true);oReq.responseType = 'json';oReq.send();

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.