JSON data is converted between the frontend (JavaScript) and backend (PHP ).

Source: Internet
Author: User
Tags php array to json scalar
Objective: To exchange frontend and backend data  Ideas:What is the JSON data format? How can I convert my content into JSON format in various backend languages? How does the front end receive JSON data? How can this problem be solved? In JS, how does one convert JSON data into an array in JS and use it as an object? Problem Encountered: The data received using Ajax is directly assigned to the variable, and an array is found in it. I don't know how to transmit data in PHP? (Or how does Ajax XMLHTTP. responsetext obtain backend data ?) PHP converts objects and arrays into JSON data formats. Learning Process: 1. knowledge popularization of JSONIn terms of structure, all data can be divided into three types:
The first type is scalar (scalar), which is a separate string or number (numbers), such as the word "Beijing.
The second type is sequence (sequence), that is, several related data are listed in a certain order, also called array or list, for example, "Beijing, tokyo ".
The third type is mapping, that is, a name/value pair (name/value), that is, the data has a name and a value corresponding to it, this is also called hash or dictionary, for example, "capital: Beijing ".
JSON (JavaScript Object Notation) is a lightweight data exchange format, and its rules are very simple:
1) Separate the parallel data with commas.
2) The ing is represented by a colon.
3) The set (array) of the parallel data is represented by square brackets.
4) The ing set (object) is represented by braces.
According to this rule, we can understand the following:
1. an array is created with "[]", an object is created with "{}", and JSON is basically an array or object created with [] or, otherwise, a normal string is meaningless;
2. Elements of arrays and objects are separated by commas;
3. Inside the object, the (attribute) names and values are separated by ":" and must be separated by ":". Attribute names or values cannot exist separately;
4. objects and arrays can be nested, that is, an element in an array can be an object or an array. Likewise, the value of an attribute in an object can be an object or an array.

2. Application of JSON in Ajax
The client can easily submit data to the server through the address bar or post. However, after the server completes data processing, it is difficult to return the calculated result information to the client, especially when the data volume is large. At this time, the data format becomes the key. According to a specific format, data can be easily assembled and then parsed conveniently. JSON is a good strategy. On the server side, a string is assembled in JSON format and returned to the client. How do I parse the client? Generally, there are two strategies (the names of the two strategies are their own names, which are not necessarily reasonable, but the idea should be correct ):

1. Direct Parsing
VaR JSON =Eval('+ Result + ')');
Through the above expression, the JSON string that the server returns to the client is parsed into a JSON (Format) object named "JSON" and passed "JSON. or "JSON.
2. Indirect Parsing
VaR JSON = "r =" + result;
Eval (JSON );
Of course, the above line of code can be merged into: eval ("r =" + result );
Through the above calculation, you can also parse the JSON string returned by the server to the client into a JSON (Format) object, but the object name is "r ", through "R. or "R.
Summary: JSON is a simple data exchange format. It can replace XML to allow flexible data exchange between servers.

3. arrays and objects in Javascript
In JavaScript, the data format created by [] is usually called an array, and what is created by {} is called an object.

There is an array A = [,], and an object A = {,}, run alert (A [1]), in both cases, the running results are the same! This means that the data set can be represented by arrays or objects. Which one should it be used?
In fact, arrays represent the set of ordered data, and objects represent the set of unordered data. If the order of data is important, use an array. Otherwise, use an object.
However, another difference between an array and an object is that the data in the array does not have a "name" and the data in the object has a "name ). But the problem is that many programming languages have something called associativearray. The data in this array is named. For example, in Javascript, you can define an object as follows:
VaR A = {"city": "Beijing", "area": 16800, "Population": 1600 };
However, it can also be defined as an associated array:
VaR A = new array ();
A ["city"] = "Beijing ";
A ["area"] = 16800;
A ["Population"] = 1600;
It seems that there is no difference between arrays and collections. Actually, no. In JavaScript, an associated array is an object, and an object is an associated array. There is a big difference between an array created in the second method and an array created in the [] method. In the "array" created in the second method, you can also use the ". city to get "Beijing", ". population "to get" 1600 ", but it is different from the object created in the first method. The first method defines a without the Length attribute, second, the second method defines a as yes, but the value is 0. The difference is still visible. To be specific, I'm afraid I have to look at some of the underlying implementation code.

4. Conversion between PHP arrays and JSON

JSON is often used because of data interaction between programs and JS functions when Ajax objects are used. Because JS does not know arrays in PHP, PHP does not know arrays or objects in Js. JSON solves this problem.

Convert arrays to JSON in PHP 
Powerful php provides built-in functions:Json_encode () and json_decode (). It is easy to understand that json_encode () is to convert the PHP array to JSON. On the contrary, json_decode () converts JSON to a PHP array.

$array = array("name" => "Eric","age" => 23);   echo json_encode($array);

The program will print: {"name": "Eric", "age": 23}

$array = array(0 => "Eric", 1 => 23);   echo json_encode($array);

The program will print out: ["Eric", 23]

The above two examples show that if the keys of the PHP array are numbers, then json_encode () returns an array of JSON, if the keys of the PHP array are all strings. Then json_encode () returns an object-type JSON. I already said. The two are called differently in Js.

Other back-end languages should have corresponding functions to process JSON data.

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.