欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

遍历JSON

程序员文章站 2022-07-12 15:51:41
...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <HEAD>
  <TITLE>遍历JSON</TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 <script language="javascript">
 function e(){
    var json = [{"id":"2","title":"Test date","content":"Test date"},{"id":"2","title":"Test","content":"Test"}]
    var str = "$";
    for (var one in json){
        for(var key in json[one]){
            str += "," + json[one][key];alert(one+"::"+key);
        }
    }
    document.form.txtName.value = str.replace(/\$,/g,"");
 }
 </script>
 </HEAD>

 <BODY>
<form name="form">
  <a href="#" onclick="e();">Click</a>
  <br>
  <input name="txtName" value="" type="text" size="50">
  </form>
 </BODY>
</HTML>

 

 

说明:使用for (var one in 数组对象)对数组遍历时,one是序号

         使用for(var key in json对象)对JSON对象遍历时,key是名值对的名字