-2

在组织更改时调用一个函数,其中选择的值存储到变量 org 中,并将选择的值与整个 json 进行比较,并且与所选组织对应的所有位置都打印在位置下拉列表中。这是我的代码

 var json = <?php echo $response ?>;
alert(json);
alert(json.length);
var org=document.getElementById('category_id').value;
alert(org);
for(var i=0;i<json.lenght;i++)
    {


    }
for(var i=0; i<json.length; i++)
    {
        var item = json[i];
        alert(item);   
}
}

my json is 

 [{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}] 

我的表单是我解析上述 json 并在我的 php fprm 中包含组织选项的地方,如下所示我还有 2 个位置和建筑物选项,这是我的表单,我的问题是当我选择一个组织时,选择的值是存储在变量中,并且该变量必须在 json 中搜索该特定值,并将包含所选组织的对象对象中的相应位置返回到下拉保存位置

<label for="orgname">Organisation Name</label>
                    <select style="width: 305px;text-align:left ;"  name="category_id" id="category_id" onchange="return orgname(this)";>
                    <option value="">Select</option>
                    <?php foreach($org as $key=>$val){?>
                    <option value="<?php echo $val; ?>"><?php echo $val;?></option>
<?php
}
?>                      </select>

                    <p>
        <label name="location">Location</label>

                     <select style="width: 305px;" name="category_id1" id="category_id1">
                     <option value="">Select</option>

                     </select>
                    </p>
                    <p>
        <label for="building">Building</label>

                    <select style="width: 305px" name="category_id2" id="category_id2" onchange="ajax(this);">
                    <option value="">Select</option>

                    </select>
4

1 回答 1

0

尝试这个

<script>
function orgname($org){    
    $org=$org.value;
var jsontext = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}] ';
var newArr = JSON.parse(jsontext);
    for($i=0;$i<=newArr.length;$i++)
    {
        if(newArr[$i].name==$org)
        {
            document.write("location Name:"+newArr[$i].location[0].name+"</br>");//for location
            document.write("building Name:"+newArr[$i].location[0].building+"</br>");//for building
        }    

    }    

}
</script>
于 2013-04-12T10:12:08.707 回答