Understanding Ajax, Part 1: Using JSON for data transmission

Source: Internet
Author: User
In asynchronous applications ProgramWhen sending and receiving information, you can select plain text and XML as the data format. This phase of understanding Ajax discusses another useful data format, JavaScript Object Notation (JSON), and how to use it to move data and objects more easily in applications.

If you have readArticleThe data format should have a considerable understanding. The previous article explains how to properly use plain text and simple name/value pairs in many asynchronous applications. Data can be combined into the following form:

Firstname = Brett & lastname = Mclaughlin & Email = brett@newInstance.com

In this way, you do not need to do anything else. In fact, the Web veteran will realize that the information sent through the GET request adopts this format.

Then, XML is discussed in this series. Obviously, XML has received a lot of attention (both positive and negative comments) and has been widely used in Ajax applications. For more information about how to use the XML data format, see the previous articles in this series:

<Request> <firstname> Brett </firstname> <lastname> McLaughlin </lastname> <email> brett@newInstance.com </Email> </request>

The data here is the same as the data shown above, but this time the XML format is used. This is nothing remarkable; it is just another data format that enables us to use XML instead of plain text and name/value pairs.

This article discusses another data format,JavaScript Object Notation(JSON). JSON looks familiar and unfamiliar. It provides another option. It is always good to select a wider range.

Significance of Selection

Before going into the details of the JSON format, you should understand why you should use two articles to discuss another data format (yes, the next article in this series also discusses JSON ), especially when you have learned how to use XML and plain text name/value pairs. In fact, the reason is very simple: the more you choose to solve any problem, find the problemBestThe more likely the solution is to be usedOneThe solution is much better.

Review name/value pairs and XML

This series has used a lot of space to discuss scenarios suitable for using name/value pairs and XML. Always consider using name/value pairs first. For problems in most asynchronous applications, using name/value pairs is almost always the easiest solution, and it only requires a very basic JavaScript knowledge.

In fact, unless there are some restrictions that force you to switch to XML, you do not need to consider using other data formats. Obviously, if you want to send data to a server program that requires XML format input, you want to use XML as the data format. However, in most cases, XML is a better choice for servers that need to send multi-segment information to applications. In other words, XML is generally better suitedDirectionThe Ajax application responds, insteadSlaveThe Ajax application sends a request.

Add JSON

When using name/value pairs or XML, you actually use JavaScript to retrieve data from the application and convert the data to another data format. In these cases, JavaScript, as a data manipulation language, is used to move and manipulate data from web forms, and convert the data into a format suitable for sending to the server program.

However, sometimes Javascript is not just used as a formatting language. In these cases, the object in Javascript is used to represent data, not only to put data from web forms into the request. In these cases, extract data from the JavaScript Object, and then put the data into the name/value pair or XML.One click. JSON: JSON allows you to easily convert JavaScript objects into data that can be sent along with the request (both synchronous and asynchronous ).

JSON is not a magic bullet, but it is a good choice for some very special situations. Do not consider that you will not encounter these situations. Read this article and the next article to learn about JSON. In this way, you will know what to do when you encounter such problems.



Back to Top

JSON Basics

Simply put, JSON can convert a set of data represented in a javascript object to a string, and then it can be easily passed between functions, alternatively, the string is transmitted from the Web Client to the server in an asynchronous application. This string looks a bit odd (several examples will be seen later), but javascript can easily explain it, and JSON can represent a more complex structure than name/value pairs. For example, it can represent arrays and complex objects, not just a simple list of keys and values.

Simple JSON example

In the simplest form, you can use the following JSON to represent name/value pairs:

{"Firstname": "Brett "}

This example is very basic and actually takes more space than the equivalent plain text name/Value Pair:

Firstname = Brett

However, when multiple name/value pairs are concatenated, JSON will reflect its value. First, you can createRecordFor example:

{"Firstname": "Brett", "lastname": "McLaughlin", "email": "brett@newInstance.com "}

In terms of syntax, this is not a great advantage over name/value pairs, but JSON is easier to use and more readable in this case. For example, it explicitly indicates that the above three values are part of the same record; curly braces make these values have a certain relationship.

Array of Values

To represent a group of values, JSON not only improves readability, but also reduces complexity. For example, assume that you want to list a person's name. In XML, many start and end tags are required. If a typical name/value pair is used (like the name/value pair seen in the previous articles in this series ), you must create a proprietary data format or change the key namePerson1-firstNameThis form.

If JSON is used, you only need to group multiple records with curly braces:

{"People": [{"firstname": "Brett", "lastname": "McLaughlin", "email": "brett@newInstance.com" },{ "firstname ": "Jason", "lastname": "Hunter", "email": "jason@servlets.com" },{ "firstname": "elliotte", "lastname": "Harold ", "email": "elharo@macfaq.com"}]}

This is not hard to understand. In this example, there is only one variable named People . The value is an array containing three entries, and each entry is a record of one person, it contains the name, last name, and email address. The preceding example demonstrates how to use parentheses to combine records into a value. Of course, you can use the same syntax to represent multiple values (each value contains multiple records):

{"Programmers": [{"firstname": "Brett", "lastname": "McLaughlin", "email": "brett@newInstance.com" },{ "firstname ": "Jason", "lastname": "Hunter", "email": "jason@servlets.com" },{ "firstname": "elliotte", "lastname": "Harold ", "email": "elharo@macfaq.com"}], "Authors": [{"firstname": "Isaac", "lastname": "Asimov", "genre ": "Science Fiction" },{ "firstname": "tad", "lastname": "Williams", "genre": "Fantasy" },{ "firstname ": "Frank", "lastname": "Peretti", "genre": "Christian fiction"}], "musicians": [{"firstname": "Eric ", "lastname": "Clapton", "instrument": "Guitar" },{ "firstname": "Sergei", "lastname": "Rachmaninoff", "instrument ": "Piano"}]}

The most noteworthy here is that it can represent multiple values, and each value contains multiple values. However, you should also note that the actual name/value pairs in the record can be different between different primary entries (programmers, authors, and musicians. JSON is completely dynamic and allows you to change the data representation mode in the middle of the JSON structure.

When processing data in JSON format, there are no predefined constraints to be observed. Therefore, in the same data structure, you can change the way data is represented, or even express the same thing in different ways.



Back to Top

Use JSON in Javascript

After mastering the JSON format, it is easy to use it in JavaScript. JSON is a javascript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.

Assign JSON data to a variable

For example, you can create a new JavaScript variable and assign a value to the JSON-format data string:

VaR people = {"programmers": [{"firstname": "Brett", "lastname": "McLaughlin", "email": "brett@newInstance.com" },{ "firstname ": "Jason", "lastname": "Hunter", "email": "jason@servlets.com" },{ "firstname": "elliotte", "lastname": "Harold ", "email": "elharo@macfaq.com"}], "Authors": [{"firstname": "Isaac", "lastname": "Asimov", "genre ": "Science Fiction" },{ "firstname": "tad", "lastname": "Williams", "genre": "Fantasy" },{ "firstname ": "Frank", "lastname": "Peretti", "genre": "Christian fiction"}], "musicians": [{"firstname": "Eric ", "lastname": "Clapton", "instrument": "Guitar" },{ "firstname": "Sergei", "lastname": "Rachmaninoff", "instrument ": "Piano"}]}

This is very simple; nowPeopleContains the preceding JSON data. However, this is not enough, because the data access method does not seem obvious.

Access Data

Although it does not seem obvious, the long string above is actually an array. After you put this array into the Javascript variable, you can easily access it. In fact, you only need to use the dot notation to represent array elements. Therefore, to access the first project name in the programmers list, you only need to use the following in javascript:Code:

People. Programmers [0]. lastname;

Note that the array index starts from scratch. Therefore, this line of code first accessesPeopleThe data in the variable.ProgrammersAnd then move to the first record ([0]); Finally, accessLastnameKey value. The result is the string value "McLaughlin ".

The following are examples of using the same variable.

People. authors [1]. genre // value is "Fantasy" people. musicians [3]. lastname // undefined. this refers to the fourth entry, and there isn't one people. programmers. [2]. firstname // value is "elliotte"

With this syntax, You can process data in any JSON format without using any additional JavaScript toolkit or API.

Modify JSON data

Just as you can access data with periods and parentheses, you can easily modify the data in the same way:

People. Musicians [1]. lastname = "Your maninov ";

After converting a string to a JavaScript Object, you can modify the data in the variable as follows.

Convert back to string

Of course, if you cannot easily convert an object back to the text format mentioned in this article, all data modifications are of little value. In JavaScript, this conversion is also very simple:

String newjsontext = people. tojsonstring ();

That's all! Now you can obtain a text string that can be used anywhere. For example, you can use it as a request string in an Ajax application.

More importantly, you canAnyThe JavaScript Object is converted to JSON text. It is not only applicable to variables that are originally assigned values using JSON strings. ToMyobjectTo convert objects, you only need to execute commands in the same form:

String myobjectinjson = myobject. tojsonstring ();

This is the biggest difference between JSON and other data formats discussed in this series. If JSON is used, you only need to call a simple function to obtain formatted data and use it directly. For other data formats, the conversion between the original data and the formatted data is required. Even if you use an API like Document Object Model (which provides a function to convert your data structure to text), you also need to learn this API and use the object of the API, instead of using native JavaScript objects and syntaxes.

The final conclusion is that if you want to process a large number of JavaScript objects, JSON is almost certainly a good choice, so that you can easily convert the data to a format that can be sent to the server-side program in the request.



Back to Top

Conclusion

This series has spent a lot of time discussing data formats, mainly because almost all asynchronous applications ultimately need to process data. If you have mastered various tools and technologies for sending and receiving all types of data and use them in the most appropriate way for each type of data, you will be more proficient in Ajax. On the basis of understanding XML and plain text, you can master JSON to process more complex data structures in JavaScript.

The next article in this series will discuss issues other than sending data and introduce how server programs receive and process data in JSON format. We also discuss how server programs can send back data in JSON format across scripts and server components, so that XML, plain text, and JSON requests and responses can be combined. This provides great flexibility and can be used in combination with almost any combination of these tools.

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.