根据 json 响应选择单选按钮

Select radio buttons based on json response

本文关键字:单选按钮 选择 响应 json 根据      更新时间:2023-09-26

我能否获得一些想法或示例,说明如何填充从数据库加载的数据的单选按钮的检查状态?

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

在成功回调中,您可以简单地迭代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);
});
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')
} )

也许这样的东西对你有用...

在 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/

尝试这样的事情:

$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。

大帝。