我的json_encode()问题?

时间:2011-07-15 10:15:22

标签: php codeigniter jquery

结果为什么json_encode()彼此相邻?

PHP:

function search_hotel(){
        $search_term = $this->input->post('search_hotel');
        $query = $this->db->order_by("id", "desc")->like('name', $search_term)->get('hotel_submits');
        $data = array();
        foreach ($query->result() as $row)
        {
           $data[] = $row->name;
        }
        echo json_encode(array('name' => $data));
// echo: {"name":["333333","\u0633\u0644","\u0633\u0644\u0627\u0633\u06cc","\u0633\u0644\u0627\u0633\u0633","\u0633\u0644\u0627\u0645"]}
    }

JS:

$('#hotel').keyup(function () {
    var dataObj = $(this).closest('form').serialize();
    $.ajax({
        type: "POST",
        url: 'http://localhost/Siran-mehdi/admin/tour/search_hotel',
        data: dataObj,
        cache: false,
        dataType: 'json',
        success: function (data) {
            $(".list_name").toggle().html('');

            $.each(data.name, function(a,b){
                $(".list_name").append('<p>' + data.name + '</p>');
            });            
        },
        "error": function (x, y, z) {
            // callback to run if an error occurs
            alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
        }
        });
    });

这是有问题的搜索结果:

http://i.stack.imgur.com/mObpn.gif

我希望你理解我的意思。

1 个答案:

答案 0 :(得分:1)

$.each为您提供一次元素。你需要做

        $.each(data.name, function(a,b){
            $(".list_name").append('<p>' + b + '</p>');
        });