在选择更改时操纵Json数组

时间:2015-11-04 22:15:35

标签: javascript php jquery json ajax

我是JQuery的新手,我想知道他是否有可能。 我有一个PHP控制器,它将一个json编码的数组发送到视图, 这是json数组:

{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}

现在在视图中我有以下内容:

<select id="selector">
<option value="">Select one</option>
<option value="1">blue</option>
<option value="8">green</option>
<option value="14">red</option>
</select>

<div id="description">

</div>

我想要做的是首先从json数组中填充选择列表,然后如果我从下拉列表中选择绿色,则绿色的描述应该出现在div上,如果我更改了我的选择,则应该在DIV。 我选择的选项应该不再出现在选择列表上,就像我选择绿色一样,只有红色和蓝色应出现在可用选项上,如果我选择另一种颜色,请说蓝色,然后红色和绿色应该可用于另一个选择。

我目前正在运行一个关于select的更改的新查询,但是我想在没有其他查询和页面刷新的情况下执行它,我想我可以将JSON数组发送到浏览器。

希望我清楚我的问题,谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

var data = [{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}];
var selector = $('#selector');

data.forEach(function(obj){
   // create option
   var option = $('<option>');
   // set its value
   option.val(obj.id);
   // set its text
   option.text(obj.text);
   // append it to select element
   selector.append(option);
}    
selector.change(function(){
    var value = this.value;
    // show all options
    selector.find('option').show();
    // hide the selected
    $(value).hide();
    // find the selected object
    var selected = data.filter(function(obj){
       return obj.id == value;
    });
    // if returns exactly one show its description
    if (selected.length == 1)
        $('#description').text(selected[0].description);
});

答案 1 :(得分:0)

首先,Json必须是这样的:

[{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}]

这是我试过的一些代码,我认为它会对你有所帮助:

$(document).ready(function(e){
     $("#selector").on('change',function(){ 
      var dataL= $("#selector option:selected").val();
      $.post("Page_json.php",{myVal:dataL},function(data,message,xhr){
                            if(message==='success'){
                                $.each(data, function(k,v){
                                    if(v.id == dataL){
                                        $("#description").text(v.description);
                                        return false;
                                    }
                                });
                            }
                        },'json');


    });
});