根据json响应选择单选按钮

时间:2012-04-18 14:44:06

标签: php javascript jquery ajax json

我是否可以获得一些想法或一个示例,说明如何根据从数据库加载的数据填充选中的单选按钮状态?

例如,我从SELECT查询生成一个类似于:

的数组
array(
[0] => array(    
    ['note_id'] => 1
    ['value'] => 'no'
  )
[1] => array(
    ['note_id'] => 4
    ['value'] => 'yes'
  )
[2] => array(   
    ['note_id'] => 5
    ['value'] => 'yes'
  )
)

复选框组如下所示:

<input type="radio" name="1" value="yes">
<input type="radio" name="1" value="no"> 
<input type="radio" name="1" value="done">

<input type="radio" name="2" value="yes">
<input type="radio" name="2" value="no"> 
<input type="radio" name="2" value="done">

现在使用json_encode我将结果的数据数组放入:

[{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}]

我通过ajax传回这些结果......类似的东西? :

$j.ajax({
    url: readurl,
    type: "GET",
    data: 'sku=' + thisSku,
    dataType: "json",
    success: function (data){
        // ? now what
    }       
});

有人可以帮助我理解我现在可以如何选择适当的json数据吗?如果note_id与输入[name]属性匹配,我将如何创建运行检查的循环?如果是,请检查具有适当值的按钮? json甚至是处理这个的最好方法吗?我应该使用.getJSON()吗?

4 个答案:

答案 0 :(得分:6)

在成功回调中,你可以简单地遍历data [{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}]

DEMO

$.each (data, function (i, obj) {
    $(':radio[name=' + obj.note_id + '][value=' + obj.value + ']').prop('checked', true);
});

答案 1 :(得分:2)

var data = {"nodes": [{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}] }

$('input:radio').attr('checked','')
$.each(data.nodes,function(a,b){
  $("input[name="+b.note_id+"][value="+b.value+"]:radio").attr('checked','checked')

} )

也许这样的事情会对你有用......

答案 2 :(得分:2)

在json对象上创建$ .each()循环,然后将note_id与名称值进行比较并添加属性

var notas = [{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}];


$.each(notas,function(i, v){
    $('input[type=radio][name=' + this.note_id + ']').prop('checked','true');

});
​

http://jsfiddle.net/chepe263/wLDHk/

答案 3 :(得分:0)

尝试这样的事情:

$j.ajax({
    url: readurl,
    type: "GET",
    data: 'sku=' + thisSku,
    dataType: "json",
    success: function (data){
        $.each(data, function(i, item) {
            alert("note_id: " + item.note_id + ", value: " + item.value);
        });
    }       
});

您必须使用代码替换de alert。

Greatings。

相关问题