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']));
}
  • 写回答

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));
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?