/* Link from: http://www.ibm.com/developerworks/cn/opensource/os-php-v523/
* Author profile: Tracy Peterson (tracy@tracypeterson.com), freelance writer, Consultant. From
* Since 1997, Tracy Peterson has been an IT project manager and Web developer.
* Head of Microsoft's MSN Search computing program. He is currently working in San Francisco.
* Finishing staff: Luo Dong ld5202@126.com
*/
Getting started with Ajax
Ajax, as an excellent method for creating fully functional Web applications, uses the power of XML to separate data forms from functions, breaking Web browser rules and restrictions, this improves the overall speed of the Internet. The main limitations of Ajax include processing XML in JavaScript. XML also makes itself very complicated. After you make sure that the XML document format is correct and error processing is set, you must still put XML into a JavaScript available object. Integrating XML into an application is not as simple as it sounds.
Since XML is not originally available in JavaScript, we 'd better use the inherent language of XML, such as PHP and simple data that is converted to the inherent format of JavaScript.
Another problem we encounter is that we do not always want or need to convert the data into XML before loading the data into the Ajax application. However, before Ajax developers can use the data we provide, we need to follow the standards. Once we create an object in PHP code, we can serialize it and export it to the Ajax section of the application for processing and retrieval.
JSON
JSON is a protocol designed to allow middleware to create objects in the inherent JavaScript format. Its most powerful property is that it is a lightweight protocol. When you simply process RSS aggregation or recipe lists, you do not need to use all the XML functions in JavaScript. You do not need to verify the format or make sure that the data is strictly typed. We can skip a lot of work related to processing XML, even if the term Ajax includes XML. To write more concise code, you can use JSON to simplify the process. Let's take a look at a simple XML document example that shows data from the RSS digest database application.
Listing 1. XML format example
Listing 1-XML Format Example
<? Xml version = "1.0"?>
<Root>
<Feed>
<Id> 21 </id>
<Url> www.blah.com/story1.html </url>
<Title> JSON is sweeping AJAX world </title>
<Viewed> FALSE </viewed>
</Feed>
<Feed>
<ID> 22 </ID>
<URL> www.blah.com/story2.html </URL>
<Title> JSON is great </title>
<Viewed> false </viewed>
</Feed>
</Root>
To obtain this XML document, we need to access the database, retrieve the relevant data, and use PHP to set the format in this XML document. Although AJAX can use XML, it is not necessary in most cases. The load bandwidth required by the control structure is unnecessary for simple applications that only need to share some links. In addition, we must recursively process MySQL results, delete invalid characters, and build our XML documents in a bit.
JSON will help in this case, because we can use json_encode () to serialize any PHP Object so that the object can be converted to a JSON protocol string for the Ajax application to read. This is much easier than creating an XML document, because we only need to pass the MySQL results directly to the function. Because MySQL results are passed in the form of a Union array, there is no intermediate step.
Let's take a look at what will happen if the above XML document is converted to a JSON object (see Listing 2 ). Currently, the database and data format are arbitrary. We will learn about the actual situation in the following sections.
Listing 2. php example of converting XML to JSON
<? PHP
// We assume that $ results is the result of an SQL query but we will construct it now
$ Results = array ("21" => array ("url" => "www.blah.com/story1.html ",
"Title" => "JSON is sweeping Ajax world ",
"Viewed" => false), "22" => array ("url" => "www.blah.com/story2.html ",
"Title" => "JSON is great", "viewed" => false ));
// We now have a populated array object in $ results resembling a possible MySQL result
$ JsonObject = json_encode ($ results );
Echo $ jsonObject;
?>
Can all of them be understood? The result does not use recursion. No tag is added. You only need to pass it into the json_encode () function, and then it will be passed out from the other end as a JSON serialized object. See listing 3 to view new objects.
Listing 3. JSON serialized XML Object example
{"21": {"url": "www.blah.com \/story1.html", "title": "JSON is sweeping AJAX
World "," viewed ": false}," 22 ": {" url ":" www.blah.com \/story2.html ",
"Title": "JSON is great", "viewed": false }}
We have a string that contains an array object and serialized in JSON format. Note the following points for this string: The encode function has automatically escaped the forward slash as a backslash, and the variable type can be identified, depending on whether quotation marks are used. Because all ID numbers in the array use quotation marks, all ID numbers are recognized as strings. All Boolean false elements are retained as boolean.
Now we have serialized the object. We can use it in any number of JSON functions of Ajax applications.
Encoding and decoding
Two functions are used for JSON: encode and decode. As you can imagine, the first function will convert any type of data objects into a group of serialized data for JavaScript processing. The second function decodes the serialized data and converts it to a basic PHP object or a union array. We have seen examples of using json_encode (), so let's take a look at json_decode ().
Listing 4. Example of json_decode ()
<? Php
$ JsonObject = '{"21": {"url": "www.blah.com \/story1.html", "title": "JSON is sweeping AJAX
World "," viewed ": false}," 22 ": {" url ":" www.blah.com \/story2.html "," title ":" JSON is
Great "," viewed ": false }}';
$ DecodedObject = json_decode ($ jsonObject );
$ DecodedArray = json_decode ($ jsonObject, true );
Print_r ($ decodedObject );
Echo "<br> ";
Print_r ($ decodedArray );
?>
As shown above, we have a PHP script that retrieves $ jsonObject and decodes it back to the inherent PHP Object. We decoded it twice. For the first time, use the unmodified usage to obtain the stdClass object. For the second time, use the Boolean parameter to create the Union array.
Listing 5. Output of Listing 4
StdClass Object ([21] => stdClass Object ([url] => www.blah.com/story1.html [title] =>
JSON is sweeping AJAX world [viewed] =>) [22] => stdClass Object ([url] =>
Www.blah.com/story2.html [title] => JSON is great [viewed] => ))
Array ([21] => Array ([url] => www.blah.com/story1.html
[Title] => JSON is sweeping AJAX world [viewed] =>)
[22] => Array ([url] => www.blah.com/story2.html [title] =>
JSON is great [viewed] => ))
We can see two objects listed using print_r.
From database to JSON
In the suggested Ajax application, our project manager wants to use data from the database provided by another application. The RSS aggregators that store the selected RSS digest results in the MySQL database of the Web server will frequently check and update RSS. To read RSS, our applications will require Ajax interfaces. As a professional backend programmer, we will focus on getting data from the database and converting it into JSON format. We will leave Ajax to experts, but we must prepare Ajax for experts to handle it.
First, we will set up the MySQL database to store the RSS abstract information, and then insert several records to prepare for the start. Then, we will write a PHP script that will enter the database and retrieve some records for the JSON-based application for use.
Set
We need to set up the MySQL database and insert some simple records for us to extract. For ease of use, we will use the database name "rss_detail" (see Listing 6 ). Since most of the major relational database management systems (RDBMS) Support PHP from the very beginning, PHP has great flexibility when selecting a database. Some RDBMS do not support PHP, but many such RDBMS can provide PHP support through abstract classes or extensions. I have used MySQL, But I can use this code to support your selected database.
Listing 6. Feeds table and SQL statement of two records
Create Table 'feeds '(
'Id' int (11) not null auto_increment,
'Url' text not null,
'Title' text not null,
'Viewed' tinyint (1) not null,
Primary key ('id ')
) ENGINE = InnoDB default charset = latin1 AUTO_INCREMENT = 3;
Insert into 'feeds '('id', 'url', 'title', 'viewed') VALUES
(1, 'www .blah.com/story1.html', 'json is sweeping AJAX world', 0 ),
(2, 'www .blh.com/story2.html', 'json is great', 0 );
We now have a database that can be accessed through a PHP script. For all database interactions, we need to set up database connections and extract data.
Listing 7. Output. php
<? Php
$ Username = "username ";
$ Password = "password ";
$ Database = "rss_agg ";
$ SQL = "SELECT * FROM 'feeds '";
Mysql_connect (localhost, $ username, $ password );
Mysql_select_db ($ database) or die ("Unable to select database ");
$ Result = mysql_query ($ SQL );
Mysql_close ();
?>
At the beginning of the output script, we only create variables to store the usernames and passwords that can access the databases on the local host. We chose the database, named rss_records, and wrote a simple SELECT statement to retrieve all records from the feeds table. The next three lines will use the connection creden。 to initiate a connection to the database, and then select the database. If this process does not occur for some reason, we will see the "Unable to select database" result. Finally, we will retrieve the SQL statement results and close the database connection.
Encoded as JSON
You need to convert the MySQL result to an available PHP Object before converting the MySQL result to a JSON string. We can convert it into an array to complete the above operations.
Listing 8. output. php with JSON code
<? Php
$ Username = "root ";
$ Password = "";
$ Database = "rss_agg ";
$ SQL = "SELECT * FROM 'feeds '";
$ Encodable = array ();
Mysql_connect (localhost, $ username, $ password );
Mysql_select_db ($ database) or die ("unable to select database ");
$ Result = mysql_query ($ SQL );
While ($ OBJ = mysql_fetch_object ($ result ))
{
$ Encodable [] = $ OBJ;
}
$ Encoded = json_encode ($ encodable );
Echo $ encoded;
Mysql_close ();
?>
We have created an array object to store the result information that json_encode () can read and convert to JSON string format. The while statement traverses each element of the result query one by one and constructs an $ encodable array row by row. After this object is completed, we only need to run it through json_encode () and generate the $ encoded object. Now, you can turn this information back to the browser and use the data from the object to respond to the requested JavaScript. The request JavaScript Application now has a completely identical copy of the PHP Object and lists the copy using a naturally understandable method of JavaScript.
Conclusion
JSON is a useful and lightweight protocol that can now be used in PHP V5.2. It can easily extract data from PHP applications and put it into Ajax applications. Correspondingly, JSON in PHP is also lightweight and useful, and contains only two easy-to-use functions. Using these functions, we can convert and export the object structure, and use json_encode () to make the data connected to the PHP database available for Ajax applications. After processing data in the Ajax application, you can return the data to the PHP script and recreate the available Object Data Structure with json_decode. After the data is returned to PHP, we can store it in the database, or use any other data processing methods provided by PHP.