根据JSON响应选择单选按钮。

3

我能否得到一些关于如何根据从数据库中加载的数据来填充单选按钮的选中状态的想法或示例?

例如,我正在从一个 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()吗?


1
展示出学习的意愿,加一分。 - Selvakumar Arumugam
4个回答

6

在成功的回调函数中,您可以简单地遍历 data,它应该是 [{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}]

演示

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

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
创建一个$.each()循环来遍历json对象,然后将note_id与name值进行比较并添加一个属性。
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/


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);
        });
    }       
});

你需要用你的代码替换掉警告。

问候。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接