Assign the PHP array to JS and implement it through the PHP system function json_encode ().

Source: Internet
Author: User

<? PHP

$ Array = array ('fds ', 'fdsa', 'fdsafasd ');
// Json_encode ($ array );

?>

<HTML>
<Head>
<SCRIPT type = "text/JavaScript">
VaR readpoint = <? PHP echo json_encode ($ array) ;?>; // *** Do not use quotation marks. If an array stored in JSON is used, it is a string. In addition, if a key name is to be displayed as an object, such as readpoint. ID
Alert (readpoint [0]); // FDS
</SCRIPT>
</Head>
</Html> [/Code]

JSON (successful test) is passed because JS can recognize data in JSON format (PHP and JS share the same thing, so passing values is effective, XML may be more difficult to advocate, even if it is possible. JSON is used for convenience. Otherwise, strings are restored to an Array Using Js .)

If JSON is not used, I have tried it but failed the test. An undefined error occurs when an element is displayed. (Test failed)

Of course, we can also use PHP arrays directly in JS without assigning values (test successful ). * ** Note that the assignment array is not a variable ***

-----------------------------------------------------

(Reference) if any problem occurs. I can achieve this through the above method.

JSON is a good data structure and is now widely used in network data transmission.

PHP has two JSON-related functions.
Json_encode and json_decode

The specific usage of these two functions is described in many related articles on the Internet.
This article describes how to convert Chinese characters when json_encode is used.

This document assumes that the file is encoded as gb2312;

Write out the required array first

<? PHP
$ JSON = array (
0 =>
Array (
'Id' => '13 ',
'Name' => 'table tennis ',
),
1 =>
Array (
'Id' => '17 ',
'Name' => 'basketball ',
)
)
?>

If the json_encode function is used directly

<? PHP

Echo json_encode ($ JSON );
?>

Result:

<? PHP
[{"ID": "13", "name": NULL}, {"ID": "13", "name": NULL}]
?>

We can see that all Chinese characters that are not escaped are null.

This is because JSON only escapes the encoding.

Therefore, the above statement should first convert the Encoding

<? PHP

Foreach ($ Ajax as $ key => $ Val)
{
$ Ajax [$ key] ['name'] = urlencode ($ Val ['name']);
}
Echo json_encode ($ JSON );

?>

Client JS Code

<SCRIPT type = "text/JavaScript">
Function getsort (OBJ)
{
$. Ajax (
{
Type: "Get ",
URL: "<? = $ This-> baseurl?> /Index/getajax ",
Data: "c =" obj. value,
Success: function (JSON)
{
VaR JSON = eval (JSON );

VaR html = '<SELECT> ';
$. Each (JSON, function (k)
{
Html = '<option value = "'json [k] ['id']'"> 'decodeuri (JSON [k] ['name']) '</option> ';
});
Html = "</SELECT> ";
('Sort'{.html (HTML );
}
}
)
}
</SCRIPT>

The above code JS reports an error saying that the encoding does not conform to the standard.

The reason is that decodeuri in JS only supports utf8 transcoding.
So
PHP
The Code should be the following code

<? PHP

Foreach ($ Ajax as $ key => $ Val)
{
$ Ajax [$ key] ['name'] = urlencode (iconv ('gb2312', 'utf-8', $ Val ['name']);
}
Echo json_encode ($ JSON );

?>

-------------------------------------------------------------------

JS reads JSON data 2010-03-22 from: blog garden font size: [large, medium, small]
  • Abstract: This article introduces how to read JSON data in Js.

Example:

<SCRIPT type = "text/JavaScript" Language = "JavaScript">
VaR versions ages = {
CN :{
Lang: 'ch ',
Name: "Chinese"
},
En :{
Lang: "English ",
Name: "en"
}
};
Document. Write (export ages.cn. Name );
</SCRIPT>

 

========================================================== ==================================
Is there a detailed example of how JS reads JSON?

// Obtain the name based on the City
Function getnamebycity (city)
{
VaR cityname =
{
"0556": "Anqing City ",
"0372": "Anyang city ",
};
Return cityname [City];
}

 

(Reference) ========================================================== ==================================
How to read JSON in JS

I have two methods for reading JSON in JS:
Method 1: function construction definition method return
VaR strjson = "{Name: 'json name'}"; // obtain the JSON
VaR OBJ = new function ("return" + strjson) (); // converted JSON object
Alert (obj. Name); // JSON name

Method 2: The famous eval function in JS
VaR strjson = "{Name: 'json name'}"; // obtain the JSON
VaR OBJ = eval ("(" + strjson + ")"); // converted JSON object
Alert (obj. Name); // JSON name

Note that the object expression {'name': 'json name'} must be expanded with "()". Otherwise
VaR strjson = "{Name: 'json name '}";
VaR OBJ = eval (strjson );
Alert (obj. constructor); // string Constructor
Alert (obj. Name); // undefine
You must extend the object expression to eval for execution to generate an anonymous object!

(Reference )--------------------------------------------------------------------------

The following JSON official JS reads the JSON structure data with Ajax.

<SCRIPT>

// Directly declare the JSON Data Structure
VaR myjsonobject = {"bindings ":[
{"Ircevent": "PRIVMSG", "method": "newuri", "RegEx": "^ http ://.*"},
{"Ircevent": "PRIVMSG", "method": "deleteuri", "RegEx": "^ Delete .*"},
{"Ircevent": "PRIVMSG", "method": "randomuri", "RegEx": "^ random .*"}
]
};

Alert (myjsonobject ["bindings"] [0]. method); // read the value of method at the first array position in the node bindings.

You can also use loops to read data.

For (var key in myjsonobject ){
Alert (myjsonobject [Key] [0]. RegEx)
}

</SCRIPT>

The following is an official json js file.

<SCRIPT src = "json2.js"> </SCRIPT>

// Rtval value: {"Digg": [{"diggnum": "12", "offnum": "0", "pageviews": "680 ", "username": "dodo"}]}

Function callback (rtval)

{

VaR myjsonobject2 = eval ("(" + rtval + ")");
Alert (myjsonobject2 ["Digg"] [0]. diggnum)

}

</SCRIPT>

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.