Here are some tips for optimizing the data format of JSONP. I hope it will be helpful to you.
When using JSON to transmit data, the field names are too repeated during list transfer, which wastes bandwidth and reduces efficiency. For example:
The Code is as follows: |
Copy code |
{ Data :[ {Name: "James", idcard :""...}, {Name: "Li Si", idcard :""...} ] } |
How many pieces of data are there, and how many sets of strings "name" and "idcard" can be simplified?
In JSONP mode, you only need to input data to a method. This data is not necessarily a direct data variable. In javascript, you can return data by calling an anonymous function, therefore, you can pass this anonymous function as an input parameter to this method:
The Code is as follows: |
Copy code |
SomeFunction (function () {return data ;})()); |
For the client web page, as long as the input data format is correct, so the data or function return value is not concerned, but for the server side, if the function is returned, you can do a lot of things, in addition, these tasks cannot be rejected by the client (because of cross-origin), including the data key redundancy problem discussed just now.
The key redundancy problem is that the key is extracted and spelled back when the function is self-executed. Therefore, two variables can be defined to store key values and data, then assemble the Code through the for Loop:
The Code is as follows: |
Copy code |
(Function (){ Var m = ["name", "idcard"]; // used to store the key name Var d = [["Zhang San", ""], ["Li Si", ""]; // It is used to store data completely without keys and without waste. Var r = {list: []}; // used to return results For (var I = 0; I <d. length; I ++ ){ R. list. push ({}); For (var j = 0; j <m. length; j ++ ){ R. list [I] [m [j] = d [I] [j]; } }; // Assemble the data back Try {return r;} finally {} // return the data required by the client }) (); // Self-executed |
If the field names are short and the number of data entries is small, you don't need to worry about it. You can directly return the data. When the amount of data is large, this method is more practical.
In addition, you can put additional code in finally, such:
Finally {alert ("although you access 163, the data is from baidu !")}
Obviously, 163 can't do anything about this: as for what to put here, it depends on the business needs. This format is now called JSONPM (JSONP Metadata extraction ).