【问题标题】:Select radio buttons based on json response根据 json 响应选择单选按钮
【发布时间】:2012-04-18 14:44:06
【问题描述】:

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

例如,我从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 向我们展示了学习的意图。

标签: php javascript jquery ajax json


【解决方案1】:

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

【讨论】:

    【解决方案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')
    
    } )
    

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

    【讨论】:

      【解决方案3】:

      在 json 对象上创建一个 $.each() 循环,然后将 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/

      【讨论】:

        【解决方案4】:

        试试这样的:

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

        伟大的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-03
          • 1970-01-01
          • 1970-01-01
          • 2013-03-04
          • 1970-01-01
          • 1970-01-01
          • 2017-06-30
          • 1970-01-01
          相关资源
          最近更新 更多