Use ajax to operate JavaScript objects, ajaxjavascript
Although it is convenient to obtain fully formatted HTML through a request, it also means that many HTML tags must be transmitted while the text content is transmitted. Sometimes we want to transmit as little data as possible and then process it immediately. In this case, we hope to obtain the data structure that can be traversed through JavaScript.
The jQuery selector can be used to traverse and operate the HTML structure. However, there is also a built-in JavaScript data format, which can reduce the amount of data transmitted and the amount of encoding.
1. Get JSON
As we have seen before, JavaScript objects are composed of some "key-value" pairs and can be easily defined using curly braces. On the other hand, JavaScript Arrays can be dynamically defined using square brackets ([]) and progressively increasing keys implicitly declared. By combining these two syntaxes, you can easily express complex and massive data structures.
S is the first letter of synchronous, that is, synchronization.
The meaning here is that if it is not Ajax, but SJAX, that is, it is not asynchronous loading, but synchronous loading, it will not have that big impact.
Douglas Crockford named JSON (JavaScript Object Notation, JavaScript Object Notation) for this simple syntax ). This representation can easily replace the XML format with a large amount of data:
Copy codeThe Code is as follows:
{
"Key": "value ",
"Key 2 ":[
"Array ",
"",
"Items"
]
}
On the basis of the object literal volume and array literal volume, the JSON format syntax has a strong ability to express, but it also has some restrictions on the value. For example, JSON requires that all object keys and all string values must be included in double quotation marks. Furthermore, the function is not a valid JSON value. Because of these restrictions, developers are advised not to manually edit the JSON, but to generate it using the server language.
To understand the syntax requirements of JSON and the advantages of JSON, see http://json.org /. If you use this format to encode the interpretation in the dictionary, there may be many encoding methods. Here, we put some dictionary entries in a json file named B. JSON. The code at the beginning of this file is as follows:
Copy codeThe Code is as follows:
[
{
"Term": "BACCHUS ",
"Part": "n .",
"Definition": "A convenient deity specified ted by ...",
"Quote ":[
"Is public worship, then, a sin ,",
"That for exceptions paid to Bacchus ",
"The lictors dare to run us in ,",
"And resolutely thump and whack us? "
],
"Author": "Jorace"
},
{
"Term": "BACKBITE ",
"Part": "v. t .",
"Definition": "To speak of a man as you find him when ..."
},
{
"Term": "BEARD ",
"Part": "n .",
"Definition": "The hair that is commonly cut off ..."
},
... File continues...
To obtain the data, you can use the $. getJS0N () method. This method will process the file after obtaining the corresponding file. After the data is returned from the server, it is a simple text string in JSON format. The $. getJSON () method parses the string and provides the processed JavaScript Object to the calling code.
2. Use the global jQuery Function
So far, all the Query methods we use need to call a jQuery object built using the $ () function. By using the selector expression, we can specify a group of DOM nodes to be operated, and then use these jQuery methods to operate them in some way. However, the $. getJS 〇 N () function is different. Logically, there is no DOM element for this method; the result object can only be provided to the script, but not to the page. Therefore, getJS () is defined as a global jQuery object (jQuery * $ object defined by the jQuery Library), that is, it is not a method of an individual jQuery object instance (that is, an object created through the $ () function.
If JavaScript Contains classes similar to those in other object-oriented languages, we can call $. getJS () A class method. For ease of understanding, we call it a global function here. In fact, in order not to conflict with other function names, all these functions use the jQuery namespace.
When using this function, we also need to pass the file name for it as before, as shown in Listing 6-3 of the Code.
Code List 6-3
Copy codeThe Code is as follows:
// Unfinished code
$ (Document). ready (function (){
$ ('# Letter-B A'). click (function (event) {event. preventDefault ();
$. GetJSON ('B. json ');
});
});
When you click the button, we cannot see the effect of the above Code. Although the function call loads a file, it does not complain about how JavaScript handles the returned data. Therefore, we need to use a callback function.
The $. getJSON () function can accept 2nd parameters. This parameter is the function called when loading is complete. As mentioned above, Ajax requests are asynchronous. The callback function provides a way to wait for data to return, rather than executing code immediately. The number of callback parameters also requires a parameter, which stores the returned data. Therefore, we need to write the code in the code list 6-4.
Code List 6-4
Copy codeThe Code is as follows:
// Unfinished code
$ (Document). ready (function (){
$ ('# Letter-B A'). click (function (event) {event. preventDefault ();
$. GetJSON ('B. json', function (data ){
});
});
});
Here we use anonymous function expressions as Callback functions, which are common in jQuery code, mainly to keep the code concise. Of course, the reference to the function declaration can also be used as a callback function.
In this way, we can use the data variable in the function to traverse the JSON data structure. Specifically, You Need To iterate the top-level array to build the corresponding HTML code for each item. Although the standard for loop can be used here, we would like to take this opportunity to introduce another practical global function of jQuery $. each (), in chapter 5th, we have seen its corresponding method. each (). $. Each () function does not operate on jQuery objects. It uses arrays or objects as the first parameter and callback function as the second parameter. In addition, you also need to take the current index of the array or object in each loop and the current item as two parameters of the callback function. See code list 6-5.
Code List 6-5
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Letter-B A'). click (function (event) {event. preventDefault ();
$. GetJSON ('B. json', function (data) {var html = '';
$. Each (data, function (entryIndex, entry) {html + = '<div class = "entry"> ';
Html + = '
Html + = '<div class = "part">' + entry. part + '</div> ';
Html + = '<div class = "definition"> ';
Html + = entry. definition;
Html + = '</div> ';
Html + = '</div> ';
});
Optional ('your dictionary'{.html (html );
});
});
});
Here, we use the $. each () function to traverse each item in sequence, and use the content of the entry object to construct an HTML code structure. After creating HTML, use .html () to insert it to <div id = "dictionary"> * to replace all the original content.
Secure HTML
This method requires that the data contains security content that can be directly used to construct HTML. For example, the data cannot contain any <character.
All that is left is to process the quote in the entry, which requires another $. each () loop. For details, refer to code checklist 6-6.
Code List 6-6
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Letter-B A'). click (function (event) {event. preventDefault ();
$. GetJSON ('B. json', function (data) {var html = '';
$. Each (data, function (entryIndex, entry) {html + = '<div class = "entry"> ';
Html + = '
Html + = '<div class = MdefinitionM>'; html + = entry. definition; if (entry. quote ){
Html + = '<div class =, quote,> ';
$. Each (entry. quote, function (lineIndex, line ){
Html + = '<div class = Hquote-lineH>' + line + '</div> ';
});
If (entry. author ){
Html + = '<div class = Hquote-authorH>' + entry. author + '</div> ';
}
Html + = '</div> ';
}
Html + = '</div> ';
});
Optional ('your dictionary'{.html (html );
});
});
});
After writing the code, you can click the next B link to verify our results. The corresponding dictionary entries appear on the right side of the page.
Although the JSON format is concise, it does not allow any errors. All square brackets, curly brackets, quotation marks, and commas must be properly and correctly used; otherwise, the file will not be loaded. Moreover, in most browsers, when the file loading fails, we cannot see any error information; the script just stops running silently.
The above is all the content of this article. I hope my friends will like it and have a new understanding of ajax operations on javascript objects.