更新时间:2021-12-05 09:10:19
使用 JSON.看看为什么 JSON over XML:http://thephpcode.blogspot.com/2008/08/why-json-over-xml-in-ajax.html
Use JSON. see why JSON over XML: http://thephpcode.blogspot.com/2008/08/why-json-over-xml-in-ajax.html
在 PHP 中简单地使用 json:
To use json in PHP simply:
<?php
echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var train = '.json_encode($array);
echo '/* ]]> */</script>';
?>
Javascript 中的变量 train
将是一个包含基于 PHP 变量 $array
的属性和数组的对象.
the variable train
in Javascript will be an object containing properties and arrays based on your PHP variable $array
.
要解析或迭代训练对象,您可以对 JSON 数组使用 for ... in
语句,对 JSON 对象直接使用 object.property.
To parse or iterate through the train object, you can use for ... in
statements for JSON arrays, and directly use object.property for JSON objects.
看到这个:
<?php
$array = array(array('id'=>3,'title'=>'Great2'),array('id'=>5,'title'=>'Great'),array('id'=>1,'title'=>'Great3'))
echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var train = '.json_encode($array);
echo '/* ]]> */</script>';
?>
输出将是:
var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];
变量 train
变成了一个对象数组.[] 方括号是数组,容纳更多的数组或对象.{} 花括号是对象,它们具有属性.
the variable train
becomes an array of objects. [] squrare brackets are arrays, holding more arrays or objects. {} curly braces are objects, they have properties to them.
所以要迭代 train
变量:
<script type="text/javascript">
var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];
for(i in train){
var t = train[i]; // get the current element of the Array
alert(t.id); // gets the ID
alert(t.title); // gets the title
}
</script>
简单!希望真的有帮助.
Simple! Hope that really helps.