使用codeigniter使用ajax / jquery将项添加到下拉列表中

时间:2014-12-30 02:35:28

标签: php jquery ajax json codeigniter

这可能是重复的问题,但我想提一下其他答案并没有解决我的问题。

正如问题所说,我想使用ajax / jquery填充下拉列表。我能够成功地以JSON格式发送和接收数据,但它不会附加下拉列表。以下是我的代码:

查看

  <select name="guard_id" id="guard_id" style="width:100%;">
    <option>select guard</option>
       <optgroup label="Previously assigned guard" id="trained_guards">
       </optgroup>
  </select>

Jquery / Ajax调用

function checkTrainedGuards(sid) {

        $.ajax({
            dataType: 'JSON',
            type: 'POST',
            url: '<?php print site_url('roster/check_trained_guards'); ?>',
            data: { sid: sid},
            beforeSend:function() {
                // this is where we append a loading image
                $('#sid').addClass('loader-roster');
            },
            success:function(data) {
             var appenddata;
             $.each(data, function (key, value) {

             appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";                        
             });
            $('#trained_guards').html(appenddata);

            },
            error:function(){
                // failed request; give feedback to user
            }
        });
    }

控制器

  public function check_trained_guards(){

        $this->load->model("guard");
        $sid=$this->input->post("sid");

        $trainedGuards=$this->guard->getGuardAlreadyWorkedOnSite($sid);

        foreach ($trainedGuards as $guard) {

        print json_encode(array(
            'gid'  => $guard->gid,
            'gname' => $guard->guard_name
        ));
        }
      }
}

当我使用firebug测试它时,我看到数据正确,它是JSON格式,如下所示:

[{"gid":"293","gname":"Abc"},{"gid":"96","gname":"guard2"},{"gid":"101","gname":"guard3"},{"gid":"91","gname":"guard4"}]

但是,我只是想知道为什么它没有将结果附加到下拉框中?

我也是alert(value.gid)jquery each loop undefined中的{{1}}进行了测试。

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

你JSON似乎格式错误。你的php部分应如下所示:

$arr = array();
foreach ($trainedGuards as $guard) {
$arr[] = $guard;

}

print json_encode($arr);

现在,此代码将返回有效的JSON,如Follows。 JOSN将显示如下所示的对象数组:

[{"gid":"2","gname":"Gurd1"},{"gid":"3","gname":"Guard2"}]

在你的ajax响应中编写以下代码

 var data = [{"gid":"2","guard_name":"Gurd1"},{"gid":"3","guard_name":"Guard2"}]; 
//This is the response format  You can also use JSON.parse if its in the string format



    var appenddata = "";
    $.each(data, function (key, value) {

    appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";                        
    });
$('#trained_guards').html(appenddata);