One problem with using JSON to pass data is that when you pass a list, the field name is too repetitive, wasting bandwidth, and reducing efficiency. Like what:
The code is as follows |
Copy Code |
{ data:[ {Name: "John", Idcard: "" ...}, {name: "Dick", Idcard: "" ...} ] } |
How many sets of data are there, "name" and "Idcard", and how many of these strings can be simplified?
In JSONP mode, only one method is required to pass in data, and this data is not necessarily a direct data variable, in JavaScript you can return the data by calling an anonymous function, so you can pass this anonymous function as an entry parameter to this method:
The code is as follows |
Copy Code |
SomeFunction (function () {return data;}) () ); |
For a client page, as long as the incoming data is in the correct format, as for whether the data or function return value is not concerned, but for the server side, if the return function, you can do a lot of things, and these things the client is unable to refuse (because Cross-domain), including the data key redundancy discussed just now.
Key redundancy problem, the most easy to think of is to extract the key, in the function from execution time to spell back, so you can define two variables to save key values and data, and then through for loop assembly, the code is as follows:
code is as follows |
copy code |
(function () { var m=["name", "Idcard"];//for saving key names var d=[["John", ""],["Dick", ""]];//fully used to store data, no key, no waste var r={list:[] };//is used to return the result 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]; } };//to assemble data back Try{return R;} finally{}//returns the data } that the client wants ();//self-executing |
If the field name is very short and the number of data bar is small, it does not need such trouble, direct return data can be, when the amount of data, this method is more practical.
In addition, you can put extra code in finally, such as:
Finally{alert ("Although you are visiting 163, but the data is from Baidu!") ”)}
Obviously 163 is powerless to do this: it depends on the business needs to put something in it. This format is called JSONPM Bar (JSONP Metadata extraction).