Use jQuery. ajaxSetup to filter request and response data.

Source: Internet
Author: User

Use jQuery. ajaxSetup to filter request and response data.

I don't know if the students have the same experience in the project process? When using ajax, You need to filter Request Parameters and response data. For example, you think that the request parameters and response information are so naked that they can be passed back and forth on the Internet, for example:

You know, in the vast Internet, all the information is insecure. What if someone peeked at us ?! It would be too embarrassing to be seen by others, to gain a glimpse of our private content, and then threaten us with this, right? At this time, you may want to encrypt the request data and response data, which is equivalent to putting a layer of clothing on our data. So we are like this:

Is it beautiful? Yes. If you wear beautiful clothes, you will not be afraid of others looking at our body. When we go out, we will wear clothes and take off our clothes when we go home, that is to say, the parameters of the ajax request need to be encrypted, and the data in the ajax response needs to be decrypted. If there are only a few ajax requests in the project that need to be encrypted, it is okay to process the data before sending the request, the success callback function decrypts responseText once. However, if the architecture is relatively large and there are more ajax requests, it is not too redundant to process encryption and decryption separately in each request response. So I will read the jQuery ajax reference manual, there are still great gains.

First, jQuery hasAjaxSetupMethod. This method can be used to set global ajax initialization parameters. That is to say, all ajax requests after the method is declared will use the initial values set by this method by default.

Then let's look at the ajax parameters. Suddenly, it's coming soon! There isBeforeSend! This function is the callback function before sending an ajax request, so we use it first:

$. AjaxSetup ({beforeSend: function () {console. log (arguments); // Let's take a look at some interesting things }});

Then we can send an ajax request:

$.ajax({    url: 'SetupServlet',    type: 'GET',    data: {     param1: 'test1',     param2: 'test2',    }   });

On the console, we can see that the printed parameter list has two objects. Let's take a look at the W3C explanation of beforeSend:

  • BeforeSend (XHR)
  • Type: Function
  • Before sending a request, you can modify the function of the XMLHttpRequest object, for example, adding a custom HTTP header.
  • The XMLHttpRequest object is a unique parameter.
  • This is an Ajax event. If false is returned, the ajax request can be canceled.

In fact, this is not correct, because XHR is not the only parameter. XHR is only arguments [0]. We also have an arguments [1]. Let's take a look at what this is:

The following items are printed in Firefox Developer Edition (the Developer version of Firefox, which has recently been found to be extremely useful:

We can see that this object is basically an ajax parameter object, because the purpose of this experiment is to dress up the data we will travel on the internet, let's see where this dress should be worn? We can see from the url of this object that the ajax operation of jQuery has serialized the parameters passed in before and attached them to the url, because this is a GET request. What is the length of the POST request? Let's try again:

$.ajax({    url: 'SetupServlet',    type: 'POST',    data: {     param1: 'test1',     param2: 'test2',     },  });

The object length of this parameter is as follows:

We can see that the POST request has a data attribute, and there is no parameter serialization string behind the url, but the data attribute is a serialized parameter string. Now we can modify the parameters before the request in the beforeSend function, modify the parameters after the url in the GET request, and modify the values in data in the POST request. The specific effect is not demonstrated here.

But here I am still not very refreshing, because whatever it is GET or POST, I GET all serialized strings. To modify parameters, we must first deserialize them before processing them, so I searched for ajax APIs again, and I foundProcessDataFirst, let's take a look at the official explanation:

  • ProcessData
  • Type: Boolean
  • Default Value: true. By default, data transmitted through the data option is converted into a query string if it is an object (technically, as long as it is not a string, with the default content type "application/x-www-form-urlencoded ". If you want to send the DOM tree information or other information that does not want to be converted, set it to false.

That is to say, by default, jQuery will automatically serialize parameters for us. Now we can set it to false to see what will happen:

$.ajaxSetup({       beforeSend: function() {         console.log(arguments);       },       processData: false,           });

The parameters in the request change as follows:

GET:

POST:

Here I only cut some parts. We can see that the parameters we passed in are native objects in the post request and finally get what I want. At this moment, I am very happy! You have to smoke a cigarette and wish a blessing. It's a blessing. So we can use this data to throw and throw at will. I want to trample on this data object! Sorry, I'm a little excited. Back to the topic, We have to dress data, right? We have to begin to take off our clothes... okay, let's start wearing clothes. Here I use base64 as an example. I encode the Request Parameters in base64 format:

$. AjaxSetup ({beforeSend: function () {console. log (arguments); var params = arguments [1]. data; var data = ''; for (var key in params) {// The two lines of code mean to perform base64 encoding var dataUtf8 = CryptoJS. enc. utf8.parse (params [key]); var dataBase64 = CryptoJS. enc. base64.stringify (dataUtf8); data = data. concat ('&' + key + '=' + dataBase64) ;}; arguments [1]. data = data. substring (1, data. length); // rewrite the serialized parameter}, processData: false ,});

Therefore, our request parameters are dressed in beautiful clothes and traveled in the Internet world, because jquery automatically attaches data to the url in the GET method, therefore, after processData is set to false, the [object] will appear after the url. This is the result after the javascript object toString (). That is to say, our method is not very suitable for the GET method, therefore, students who want to dress data should use the POST method.

Here, we have solved the problem of sending data, but what about receiving data? If the accepted data is encrypted, we still need to decrypt the data (we have to put it on our own]). We continue to read the API, so I see anotherDataFilterThings, old rules, first look at the official explanation:

  • DataFilter
  • Type: Function
  • A preprocessing function for the original data returned by Ajax. Two parameters are provided: data is the original data returned by Ajax, and type is the dataType parameter provided when jQuery. ajax is called. The value returned by the function will be further processed by jQuery.

This function is very simple. There are two parameters: arguments [0] is the original response data of ajax, that is, XHR. responseText, arguments [1] isDataTypeAnd the value returned by this function is the responseText in the success callback function. This is very easy to handle. Let's test it first:

The front-end code sends an ajax request, and the backend responds with a "hello" sentence. Then, we return a "world" sentence in dataFilter"

Front-end code:

$. AjaxSetup ({beforeSend: function () {console. log (arguments); var params = arguments [1]. data; var data = ''; for (var key in params) {// The two lines of code mean to perform base64 encoding var dataUtf8 = CryptoJS. enc. utf8.parse (params [key]); var dataBase64 = CryptoJS. enc. base64.stringify (dataUtf8); data = data. concat ('&' + key + '=' + dataBase64) ;}; arguments [1]. data = data. substring (1, data. length); // rewrite the serialized parameter}, processData: false, dataFilter: function () {console. log (arguments); // This is a habit of mine. After getting a function, take care of what it is. First, see the parameter return "world ";}}); $. ajax ({url: 'setupservlet ', type: 'post', dataType: 'text', data: {param1: 'test1', param2: 'test2',}, success: function (responseText) {console. log (responseText );},});

Background code (java ):

 String param1 = request.getParameter("param1"); String param2 = request.getParameter("param2"); System.out.println("param1: " + param1); System.out.println("param2: " + param2); response.getWriter().write("hello");

Backend output:

Frontend output:

It seems that everything is normal. Now we have a one-stop process of encryption and decryption:

Front end:

 $.ajaxSetup({        beforeSend: function () {        var params = arguments[1].data;        var data = '';        for (var key in params) {          var dataUtf8 = CryptoJS.enc.Utf8.parse(params[key]);          var dataBase64 = CryptoJS.enc.Base64.stringify(dataUtf8);          data = data.concat('&' + key + '=' + dataBase64);        };        arguments[1].data = data.substring(1, data.length);      },      processData: false,      dataFilter: function () {        var result = '';        try {          var a = CryptoJS.enc.Base64.parse(arguments[0]);          var result = CryptoJS.enc.Utf8.stringify(a);        } catch(e) {          result = arguments[0];        } finally {          return result;        }      }    });

Background:

String param1 = request.getParameter("param1");    String param2 = request.getParameter("param2");    byte[] buffer1 = Base64.decodeBase64(param1);    byte[] buffer2 = Base64.decodeBase64(param2);    System.out.println("param1: " + new String(buffer1));    System.out.println("param2: " + new String(buffer2));    response.getWriter().write(Base64.encodeBase64String("hello".getBytes()));

Background output:

Frontend output:

So far we have achieved success. Let's summarize what we have used.

First:AjaxSetupThis is the initial attribute for global settings.

Then there are three attributes:

BeforeSend:Functions executed before sending

ProcessData:Parameters are not serialized by default.

DataFilter:Filter response data

Then, we can put on a layer of beautiful clothes for our data.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.