Using Jquery.ajaxsetup to filter the request and response data _jquery

Source: Internet
Author: User
Tags base64 decrypt object object serialization

Do not know the students in the process of doing projects have the same experience it? When using AJAX, you need to filter the request parameters and response data, such as when you feel that the request parameters and response information are so naked on the internet, like this:

You know, in the vast Internet, all the information is not safe, in case someone peeping us how to do?! Wouldn't it be too embarrassing if someone else saw our body, peeped into our privacy, and threatened us? At this point, 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 do this:

is not Meimei, right, put on a layer of beautiful clothes, is not afraid of others peeping our body, we go out to wear clothes, go home to undress, that is, Ajax request parameters need to encrypt, Ajax response to the data to decrypt, If the project has only a few Ajax requests need to encrypt the words also OK, send a request before the data processing, success callback function to decrypt the responsetext again is over. But if the architecture is a bit larger, Ajax requests a little more, each request response must be handled separately encryption and decryption is not too redundant, so I went to the jquery Ajax reference Manual, there is really a small harvest.

First, jquery has a ajaxsetup method that sets the global Ajax initialization parameters, which means that all AJAX requests after the method is declared will default to the initial values set by the method.

Then we flip through the Ajax parameters, and suddenly, my eyes are bright! There is a method called beforesend , I see the name on the light! This function is the callback function before the AJAX request is sent, so we use it first:

 $.ajaxsetup ({       
      beforesend:function () {
      console.log (arguments);//Let's take a look at what's funny here
      }  );  

And then we're casually sending an AJAX request:

$.ajax ({
    URL: ' setupservlet ',
    type: ' Get ',
    data: {
     param1: ' test1 ',
     param2: ' Test2 ',
    }
});

In the console we can see that the printed argument list has two objects, so let's take a look at the interpretation of Beforesend in the consortium:

    • Beforesend (XHR)
    • Type: Function
    • You can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header.
    • The XMLHttpRequest object is the only parameter.
    • This is an Ajax event. If you return False, you can cancel this Ajax request.

It's not really right here, because XHR is not the only argument, xhr just arguments[0], we have a arguments[1], let's see what this is:

Here's what's printed in the Firefox Developer Edition (Firefox developer version, most recently discovered, Super handy):

See here we generally understand that our object is basically Ajax parameter object, because our purpose of this experiment is to give us the data that will travel in the internet to wear clothes, then we see this clothes should wear where? At the URL of this object we can see that the Ajax operation of JQuery has been serialized and appended to the URL of the parameter we passed in before because it is a GET request. So what does a POST request look like? Let's try again:

$.ajax ({
    URL: ' setupservlet ',
    type: ' POST ',
    data: {
     param1: ' test1 ',
     param2: ' Test2 ',
     },
  });

Now this parameter object looks like this:

We can see that the difference is that the POST request has one more data attribute, and there is no parameter serialization string after the URL, but the Data property is the parameter string after serialization. So far we have been able to modify the parameters before the request in the Beforesend function, the GET request to modify the parameters after the URL, POST request to modify the value in data, the effect is not shown here for the moment.

But I'm still not happy to be here. Because whether get or POST, I got the serialized string, to modify the parameters must be deserialized, and then to deal with, and then I find in the Ajax API, Kung fu not negative, I found a called ProcessData things, first take a look at the official explanation:

    • ProcessData
    • Type: Boolean
    • Default value: True. By default, data that is passed in through the data option, if it is an object (technically, as long as it is not a string), is processed into a query string to match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert.

In other words, JQuery automatically serializes the parameters by default, so let's now set it to false to see what happens:

$.ajaxsetup ({
       beforesend:function () {
         console.log (arguments);
       },
       Processdata:false,     
      });

In this case, the parameters in the request will change as follows

Get:

POST:

Here I only intercept part of the screenshot, we see the parameters we passed in the POST request is the original object, finally get what I want, at this moment my heart exultation! Have to smoke a good wish, the wrong amount ... is to wish Shunxing. So we can take this data to enjoy the ravages, random whipping, I want to the data object to trample on! Well, I'm sorry to be a little excited. Back to the point, we have to give data to wear clothes is right, how to say that we are about to start stripping clothes ... OK, let's get dressed, here I take Base64 for example, I base64 the requested parameters:

$.ajaxsetup ({
      beforesend:function () {
        console.log (arguments);
        var params = Arguments[1].data;
        var data = ';
        for (var key in params) {
          //These two lines of code mean base64 encoded
          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);//The serialized parameter overrides
      },
      Processdata:false,
    });

As a result, our request parameters are dressed in a beautiful dress in the world of the Internet, because jquery in the Get method will automatically append data to the URL, so after the ProcessData set to False after the URL will appear [object Object], which is the result of the JavaScript Object ToString (), which means that our method does not quite fit the Get method, so the students who want to dress the data are still using the POST method.

In this case, we solved the sending of the data, but what about accepting the data? If the accepted data is also encrypted, we also need to decrypt the data (speaking here or to undress [cover face]), we continue to flip through the API, so I saw a thing called Datafilter , the old rules, first read the official explanation:

    • Datafilter
    • Type: Function
    • A function to preprocess the raw data returned by Ajax. Provides data and type two parameters: Data is the original source returned by Ajax, and type is the DataType parameter provided when calling Jquery.ajax. The value returned by the function will be further processed by JQuery.

The function is simple, with two parameters, Arguments[0] is the original response data of Ajax, i.e. Xhr.responsetext, arguments[1] is the dataType of the AJAX request parameters, And this function returns the value that is the success callback function of the responsetext, this is very good to do, we first test:

The front-end code sends an AJAX request, the background responds with a "hello", and then we return a "world" in the Datafilter.

Front-End Code:

 $.ajaxsetup ({beforesend:function () {console.log (arguments);
        var params = Arguments[1].data;
        var data = '; 
          for (var key in params) {//These two lines of code mean base64 encoded 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 parameters after serialization}, Processdata:false, datafilter:funct
      Ion () {console.log (arguments); This is one of my habits, get a function, tube what he is, first look inside what parameters return to "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");

Back-end output:

Front-End output:

Seems to be all right, now we encrypt and decrypt the process of one-stop processing:

Front:

 $.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:

Front-End output:

Now that it's done, let's summarize what we've used.

First: Ajaxsetup This is the initial property that sets the global

Then there are three properties:

beforesend: function to execute before sending

processdata: default non serialization parameter

Datafilter: Filter The data for the response

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

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

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.