使用键和值将json响应打印为数组

时间:2014-01-04 20:04:51

标签: javascript php jquery json

我需要将'resulte'div中的json响应打印为与php发送的数组相同的数组。

upload.php的:

$arr=array('username'=>array('isEmpty'=>'required','exists'=>'username exists'),'password'=>array('isEmpty'=>'requiredd'));
echo json_encode($arr);

的index.php:

<script src="jquery.min.js"></script>
<script src="jquery.form.min.js"></script> 
<script type="text/javascript">
    function a(){
    $('#submitForm').ajaxForm({
        dataType: 'json',
        success: function(result){
document.getElementById('resulte').innerHTML=”I need to print the response array here like key=>value”;
                }}).submit();
         }
</script>

    <form id="submitForm" name="submitForm" action="upload.php" method="post" enctype="multipart/form-data" >
    File: <input name="myfile" type="file" />
    <input type="button" id="submitBtn" name="submitBtn" value="Upload" onclick="a();" />
    </form>
<div id="resulte" name="resulte"></div>

假设我不知道index.php中的键和值以及接收的记录数。所以我想在这里使用一些条件,如:

foreach($result as $key=>$value){
if($key==” username”){
echo $key.”=><br />”;
      foreach($value as $k=>$val){
          if($k==” isEmpty”){
             echo $k.”=>”.$val.”<br />”;
}
 }
  }
}

如何通过javascript完成所有这些操作?

-Thanks。

解决:

(根据'josh'的答案)

<script type="text/javascript">
    function a(){
    $('#submitForm').ajaxForm({
        dataType: 'json',
        success: function(result){
for (var key in result) {
  if (result.hasOwnProperty(key)) {
    if(key == "username") {
        document.getElementById('resulte').innerHTML = key + " => <br />";
        for (var k in result[key]) {
          if (k == "isEmpty") {
            document.getElementById('resulte').innerHTML += k + " => " + result[key][k] + "<br />";
          }
        }
    }
  }
}     
                }}).submit();
         }
</script>

1 个答案:

答案 0 :(得分:1)

试试这个。

var p = {"username":{"isEmpty":"required","exists":"username exists"},"password":{"isEmpty":"requiredd"}};

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    if(key == "username") {
        document.getElementById('resulte').innerHTML += key + " -> " + p[key] + "<br />";
        for (var k in p[key]) {
          if (k == "isEmpty") {
            document.getElementById('resulte').innerHTML += k + " -> " + p[key][k] + "<br />";
          }
        }
    }
  }
}