dongyata3336
2014-12-03 03:21
浏览 35

如何将选择数组从ajax传递到codeigniter视图?

I found the best answer here, but when I implemented it in my code, here's what happen to the dropdown select option:

"
1
"
:
"
t
e
s
t
1
"
,
(and so on).

What's wrong with it?

The ajax code in view:

$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/main/get_location",
data: data_loc,
success: function(locs)
{
    //alert(locs); when I do this, the alert shows: {"1": "test 1", "2": "test 2"}.
    $('#location').empty();
    $('#location').show();
    $.each(locs,function(id,location_description){
        $('#location').append($("<option></option>").attr("value",id).text(location_description));
    });
}

});

In controller:

public function get_location()
{
    $this->load->model("xms/model_db"); 
    echo json_encode($this->model_db->get_location_by_group($_POST['location_gr']));
}

图片转代码服务由CSDN问答提供 功能建议

我找到了最佳答案这里,但当我实现它时 在我的代码中,这是下拉选择选项发生的事情:


1



t
e
s
t
1


(等等)。

它出了什么问题?

视图中的ajax代码:

  $ .ajax({
type  :“POST”,
url:“&lt;?php echo base_url();?&gt; /index.php/main/get_location”,
data:data_loc,
success:function(locs)
 {
 // //  alert(locs);当我这样做时,警报显示:{“1”:“test 1”,“2”:“test 2”}。
 $('#position')。empty(); 
  $('#position')。show(); 
 $ .each(locs,function(id,location_description){
 $('#location')。append($(“&lt; option&gt;&lt; / option&gt;  ;“)。attr(”value“,id).text(location_description)); 
}); 
} 
  <  / pre> 
 
 

});

在控制器中:

 公共函数get_location()
 
 \  n $ this-&gt; load-&gt; model(“xms / model_db”);  
 echo json_encode($ this-&gt; model_db-&gt; get_location_by_group($ _ POST ['location_gr'])); 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhuiwan5141 2014-12-03 03:58
    已采纳

    This is because locs is parsed as a string but not a json object. Try put datatype in your $.ajax like this:

    $.ajax({
    type: "POST",
    url: "<?php echo base_url();?>/index.php/main/get_location",
    data: data_loc,
    dataType: 'json',
    success: function(locs, dataType)
    {
        $('#location').empty();
        $('#location').show();
        $.each(locs,function(id,location_description){
            $('#location').append($("<option></option>").attr("value",id).text(location_description));
        });
    }
    

    Or maybe using parseJSON:

    $.ajax({
    type: "POST",
    url: "<?php echo base_url();?>/index.php/main/get_location",
    data: data_loc,
    success: function(result)
    {
        loc = $.parseJSON(result);
        $('#location').empty();
        $('#location').show();
        $.each(locs,function(id,location_description){
            $('#location').append($("<option></option>").attr("value",id).text(location_description));
        });
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题