Resources from the Blog Park < original link;, organize, learn.
When it comes to Ajax, it inevitably faces two problems, the first of which is what format does AJAX exchange data for? The second is how do cross-domain requirements work? Both problems now have different solutions, such as data can be described by a custom string or XML, and cross-domain can be resolved by a server-side proxy.
The preferred solution is to use JSON to spread the data across domains by JSONP.
JSON (JavaScript Object Notation) and Jsonp (JSON with Padding): JSON is a data interchange format, and Jsonp is an unofficial cross-domain data interaction protocol that relies on the ingenuity of developers. One is the format of describing information, and the other is the method agreed by both parties to the information delivery.
Json
JSON is a type of text-based data exchange, or a data description format.
The advantages of JSON:
1, based on plain text, cross-platform transmission is extremely simple;
2, JavaScript native support, background language almost all support;
3, lightweight data format, occupies very few characters, especially suitable for internet transmission;
4, readability is strong, although less than the XML so at a glance, but in a reasonable order after indentation is easy to identify;
5, easy to write and analysis, of course, if you want to know the data structure;
The format or rule of JSON:
JSON can describe a data structure in a very simple way, and XML can do it all, so it's completely pitches in cross-platform terms.
1. JSON has only two data type descriptors, curly braces {} and square brackets [], the remaining English colons: is the map, comma, is the delimiter, the English double quotation mark "" is the definition.
2, curly braces {} are used to describe a set of "different types of unordered key-value pairs" (each key-value pair can be interpreted as an attribute description of OOP), and square brackets [] are used to describe a set of "ordered sets of data of the same type" (which corresponds to an array of OOP).
3, if there are more than one of the two sets of children, it is separated by commas.
4. The key value pairs are separated by a colon: and the key name is suggested with the English double quotation mark "" to facilitate the parsing of different languages.
5, JSON internal data type is nothing more than string, number, Boolean, date, null so several, the string must be enclosed in double quotation marks, the rest are not, the date type is special, here does not expand the narrative, but it is recommended if the client is not sorted by date function requirements, It would be nice to pass the date and time directly as a string, which would save a lot of trouble.
Example:
Php:echo Cjson::encode ($result)
Js:
$.ajax ({
Type: ' GET ',
Url:eio. Url.geteioadminemaillisturl (),
DataType: ' JSON ',
Success:function (Result) {
if (_.isfunction (callback)) {
Callback (result);
}
}
});
Getauditlogdata:function (callback, conditions) {
$.getjson (
Eio. Url.getreportlisturl (),
Conditions
function (Result) {
if (_.isfunction (callback) && Result.status = = ' success ') {
Callback (Result.data, Result.totalcount);
}
}
);
},
Resendemail:function (ID, callback) {
$.ajaxsettings.async = false;
$.post (Eio. Url.getresendemailurl (), {"id": id}, function (data) {
if (callback && (typeof callback = = = ' function ')) {
Callback (Data.status);
}
}, "JSON");
},
Jsonp
Let's talk about how JSONP is produced:
1, a well-known problem, Ajax directly request ordinary file There is no access to cross-domain issues, no matter you are static pages, dynamic Web pages, Web services, WCF, as long as the cross-domain requests, are not allowed;
2, but we also found that the Web page when the JS file is not affected by whether or not cross-domain impact (not only that, we also found that the "src" attribute of the label has the ability to cross-domain, such as <script>, , <iframe >);
3, so can judge, the current stage if you want to through the pure Web side (ActiveX control, Server Agent, belongs to the future of HTML5 WebSocket, etc.) access to data across domains is only one possibility, that is, on the remote server to try to load the data into the JS format of the file, For client invocation and further processing;
4, it happens that we already know that there is a kind of pure character data format called JSON can be concise description of complex data, even better is the JSON is also supported by JS native, so in the client can almost arbitrary processing of this format of data;
5, such a solution is to be seen, the Web client by the same way as the call script to invoke the cross-domain server dynamically generated JS format files (usually JSON suffix), it is obvious that the server to dynamically generate JSON files, The goal is to load the data that the client needs.
6, the client in the JSON file after the successful call, but also to obtain their own required data, the rest is to do their own needs to deal with and show that the way to get remote data looks very much like Ajax, but in fact, it is not the same.
7, in order to facilitate the use of data by the client, gradually formed an informal transport protocol, people call it Jsonp, one of the main points of the protocol is to allow users to pass a callback parameter to the server, The callback parameter is then used as the function name to wrap the JSON data when the server returns data, so that the client can customize its own function to automatically process the returned data.
If there is some ambiguity about how the callback parameter is used, there are specific examples to explain later.
Add
1, Ajax and JSONP the two technologies in the invocation of the way "looks" very much like, the purpose is the same, is to request a URL, and then the server to return the data processed, so the jquery and ext and other frameworks have Jsonp as a form of Ajax encapsulation;
2, but Ajax and JSONP are actually different things in nature. The core of Ajax is to obtain non-page content through XMLHttpRequest, while the core of JSONP is dynamic add <script> tag to invoke the JS script provided by the server.
3, so that, in fact, the difference between Ajax and JSONP is not whether cross-domain, AJAX through the service-side proxy can be implemented across domains, JSONP itself does not exclude the same domain data acquisition.
4, there is, Jsonp is a way or non-mandatory protocol, like Ajax, it does not have to use JSON format to pass the data, if you want to, the string is OK, but this is not conducive to the use of JSONP to provide public services.
All in all, JSONP is not a special case of Ajax, even if the giant jquery, such as Jsonp encapsulated in Ajax, can not change a bit!
Example
Php:
Public Function Actionisexistemailforjsonp ()
{
$email = Yii::app ()->request->getparam (' email ');
$jsonp = Yii::app ()->request->getparam (' Jsoncallback ');
$user = User::model ()->findbyattributes (Array (' email ' + $email, ' deleted ' + 0));
$result = Array (' status ' = = SUCCESS, ' isexist ' + = false);
if (Isset ($user)) {
$result [' isexist '] = true;
}
Echo $jsonp. ‘(‘ . Cjson::encode ($result). ‘)‘;
}
Js:
function Isexistemail (email) {
$.getjson ("http://easyio.com/user/isExistEmailForJsonp?email=" + email + "&jsoncallback=?", function (JSON) {
var isexist = json.isexist;
});
}
$.ajax({
dataType:
‘jsonp‘
,
data:
‘id=10‘
,
jsonp:
‘jsonp_callback‘
,
url:
‘http://easyio.com/user/isExistEmailForJsonp‘
,
success:
function
(){
//dostuff
},
});
JSON and JSONP