Use Ajax to manipulate JavaScript object details _ajax related

Source: Internet
Author: User
Tags data structures html tags jquery library

Getting fully formatted HTML by request is convenient, but it also means that you must transfer a lot of HTML tags while transferring text content. Sometimes we want to be able to transmit as little data as possible and then process that data right away. In this case, we want to get a data structure that can be traversed through JavaScript.
The Jqueiy selector allows you to traverse and manipulate the acquired HTML structure, but there is also a JavaScript-built data format that reduces the amount of data transferred and reduces the amount of coding.

1. Get JSON

As we've seen before, JavaScript objects are made up of some "key-value" pairs, and can be easily defined using curly braces ({}). On the other hand, an array of JavaScript can be dynamically defined using square brackets ([]) and an implicitly-declared, incrementally-incremented key. By combining these two syntaxes, you can easily express complex and large data structures.
S is the first letter of synchronous, that is, synchronization.
The author here means that if it is not Ajax, but Sjax, that is, not asynchronous loading, but synchronous loading, then it will not have so much impact.
Douglas Crockford a name for this simple syntax, called JSON (JavaScript Object notation, JavaScript objects notation). This notation makes it easy to replace the large amount of data in XML format:

Copy Code code as follows:

{
"Key": "Value",
"Key 2": [
"Array",
"Of",
"Items"
]
}

The JSON-formatted syntax has strong expressive power on the basis of object literals and array literals, but there are limits to the values. For example, JSON stipulates that all object keys and all string values must be enclosed in double quotes. Also, a function is not a valid JSON value. Because of these limitations, it is best for developers not to edit JSON manually, but rather to build it in a server-side language.

To understand the syntax requirements of JSON and what advantages it has, there are languages that support this data format, please visit http://json.org/. If you encode the interpretation in the dictionary in this format, there may be many ways to encode it. Here, we put some dictionary entries in a JSON file called B.json, and the code at the beginning of the file is as follows:

Copy Code code as follows:

[
{
"term": "BACCHUS",
"Part": "N.",
"Definition": "A convenient deity invented by the ...",
"Quote": [
"Is public worship, then, a sin,",
"That's for devotions 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 the A man as your find him when ..."
},
{
"term": "BEARD",
"Part": "N.",
"Definition": "The hair that's commonly cut off by ..."
},
... file continues ...

To obtain this data, you can use the $.getjs0n () method, which processes the file after the corresponding file is obtained. After the data is returned from the server, it is just a simple JSON-formatted text string. The $.getjson () method resolves the string and supplies the resulting JavaScript object to the calling code.

2. Using the global jquery function

So far, all of the Xun query methods we use need to be invoked through a jquery object built by the $ () function. With a selector expression, we can specify a set of DOM nodes to manipulate, and then use these jquery methods to manipulate them in some way. However, the $.getjs0n () function is not the same. Logically, there is no DOM element applicable to the method; The resulting object can only be provided to the script, not to the page. For this reason, getjs0n () is defined as a method of the global jquery object (the 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 by the $ () function).

If there are classes in JavaScript that resemble other object-oriented languages, then we can call $.GETJS0N () the class method. For the sake of understanding, we call this global function here; in fact, in order not to conflict with other function names, these global functions use the jquery namespace.

When using this function, we also need to pass the filename as before, as shown in Listing 6-3.
Code Listing 6-3

Copy Code code as follows:

Incomplete code
$ (document). Ready (function () {
$ (' #letter-B-A '). Click (Function (event) {Event.preventdefault ();
$.getjson (' B.json ');
});
});

When the button is clicked, we do not see the effect of the above code. Because the function call loads the file, it does not tell JavaScript what to do with the returned data. To do this, we need to use a callback function.
The $.getjson () function can accept the 2nd parameter, which is the function that is called when the load completes. As noted above, Ajax requests are asynchronous, and the callback function provides a way to wait for the data to return, rather than executing the code immediately. The callback function also requires a parameter that holds the returned data. So our code has to be written in code listing 6-4.
Code Listing 6-4

Copy Code code as follows:

Incomplete code
$ (document). Ready (function () {
$ (' #letter-B-A '). Click (Function (event) {Event.preventdefault ();
$.getjson (' B.json ', function (data) {
});
});
});

We use anonymous function expressions here as callback functions, which are common in jquery code, primarily to keep the code simple. Of course, a reference to a function declaration can also be used as a callback function.

In this way, we can traverse the JSON data structure through the data variable in the function. Specifically, you need to iterate over the top-level array and build the appropriate HTML code for each item. Although the standard for loop can be used here, we take this opportunity to introduce another practical global function of jquery $.each (), in chapter 5th we have seen its corresponding method. each (). The $.each () function does not manipulate the jquery object, which takes the array or object as the first argument, and the callback function as the second argument. In addition, you need to use the current index of the array or object in each loop and the current item as two parameters for the callback function, see Code Listing 6-5.

Code Listing 6-5

Copy Code code 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> ';
});
$ (' #dictionary '). HTML (HTML);
});
});
});

This iterates through each item through the $.each () function and constructs the HTML code structure using the contents of the entry object. After building the HTML, you insert it into the <div id= "dictionary" >*, replacing all of the original contents with the. html ().

Secure HTML

This method requires that the data contain security content that can be used to build HTML directly, for example, that the data cannot contain any < characters.

Now all that's left is to deal with the terms in the entry, which requires another $.each () loop, see Code Listing 6-6.
Code Listing 6-6

Copy Code code 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> '; HTML + + ' </div> ';
});
$ (' #dictionary '). HTML (HTML);
});
});
});

After writing this code, you can click the next B link to verify our results, as shown in Figure 6-4, the corresponding dictionary entry appears on the right side of the page.

Although the JSON format is concise, it does not allow for any errors. All brackets, curly braces, quotes, and commas must be used reasonably and correctly, otherwise the files will not load. Also, in most browsers, we don't see any error messages when the file fails to load, and the script simply terminates the operation silently.

Related Article

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.