【问题标题】:Loop in a json codeigniter object with jquery使用 jquery 在 json codeigniter 对象中循环
【发布时间】:2014-05-29 21:04:58
【问题描述】:

我搜索了很多问题但对我没有用,我想遍历控制器返回的 json 对象,让我给你看代码:

型号

public function traer_pasajero($id){
    $this->db->select('*');
    $this->db->from('pasajeros');
    $this->db->where('id', $id);
    $query = $this->db->get();
    return $query->result();
}

控制器

public function traer_pasajero(){
$pasajero = $this->pasajeros_model->traer_pasajero($this->input->post('id'));
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($pasajero));
return $pasajero;
}

JS

function modificarPasajero (id) {

   $.ajax({
     type: "POST",
     url: "http://localhost/xxx/xxx/traer_pasajero", 
     data: {id: id},
     dataType: "text",  
     cache:false,
     success: 
          function(data){

            $.each( data, function( key, value ) {
            alert(value);
            });
          }
     });

}

我在 firebug 中收到此错误: TypeError: 'in' 操作数 a 无效

这是我在 firebug 中看到的 json 对象:

[{"id":"1","primer_nombre":"xxxx","segundo_nombre":"","primer_apellido":"xxxx","segundo_apellido":"","ci":"xxx" ,"nacionalidad":"乌拉圭","fecha_nacimiento":"5/7/1910","vencimiento":"5/5/1910","asiento":"12","habitacion":"Sgl"," levante":"","telefono":"","observaciones":"","id_envio":"2"}]

【问题讨论】:

    标签: javascript php jquery json codeigniter


    【解决方案1】:

    dataType 应该是"json" 而不是"text",并在每个循环之前尝试console.log(data)。

    【讨论】:

    • [Object { id="1", prime_nombre="xxx", prime_apellido="xxx", más...}] 向我展示了这一点,但我该如何迭代?
    • 好的,JSON 响应看起来不错。使用 $.each(data, function( key, value ) { ... }); 进行迭代,就像你已经尝试过的那样
    • 我在 each 中设置了 alert(value) 并返回 [object Object],可以吗?
    • 是的,这不是 alert() 函数的预期行为。如果要查看数据,请尝试 console.log('Key: '+key+', Value: '+value);这是您应该对这些数据做一些事情的地方,例如将其显示给用户或其他什么。检查 jQuery 函数,例如 $(selector).html() 和 $(selector).append()...
    • 我使用 $.each(data, function(index, element) { alert(element.primer_nombre); $('#primer_nombre').val(element.primer_nombre) });然后工作!
    【解决方案2】:

    尝试删除此语句

     return $pasajero;
    

    因为它正在覆盖您的 json.. 你可以简单地返回

     return json_encode($pasajero);
    

    然后尝试 也换了

    datatype : "json"
    

    现在进行迭代,您可以使用 eval(string) 或 JSON.parse(string)。但请注意 eval 是危险的

       var obj = eval("("+data+")"); 
    

    或

       var obj = parseJSON(data);  
      $.each( obj, function( key, value ) {
            alert(value);
            });
    

    【讨论】:

    • parseJson 未定义
    • parseJSON in JSON 总是大写
    • 你也可以使用 eval one,因为你知道你在发送什么,但是当你不知道时避免 eval,在这种情况下它可以 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多