【问题标题】:outputting a bunch of json returned values输出一堆json返回值
【发布时间】:2012-09-16 22:41:15
【问题描述】:
$('.more').live("click",function() {
    var id = $('.wallPosts:last').attr("relOne");
    $.ajax({
        type: "POST",
        url: "<?=base_url()?>index.php/regUserDash/ajaxMore",
        data:  {id: id},
        cache: false,
        success: function(data) {
                $("#morebox").append(data.idWallPosts);
        }
    });
});

使用上面的代码,我将如何输出一堆 json 返回值?以下是我的 json 值:

{"idwallPosts":"803"}{"idwallPosts":"798"}{"idwallPosts":"797"}{"idwallPosts":"796"}{"idwallPosts":"793"}{"idwallPosts":"792"}{"idwallPosts":"789"}{"idwallPosts":"785"}{"idwallPosts":"780"}

下面是我的codeigniter代码:

public function ajaxMore() {
        $id = $this->input->post('id');
        $result = $this->db->query("SELECT * FROM wallposts WHERE idwallPosts < '$id' ORDER BY idwallPosts DESC LIMIT 9");
        foreach($result->result() as $row) {
            echo json_encode(array('idwallPosts' => $row->idwallPosts));
        }
    }

【问题讨论】:

  • 您的 JSON 值应列为包装在单个对象中的属性 .. {"key1":"val","key2":"val2", ...}

标签: php jquery ajax json codeigniter


【解决方案1】:

dataType:'json'添加到$.ajax的选项中,并使用success函数中的参数data作为任何其他数组对象来迭代它

$.each(data, function( .. ) { .. } ):

【讨论】:

    【解决方案2】:

    您应该将ajaxMore() 函数更改为:

    public function ajaxMore() {
        $id = $this->input->post('id');
        $result = $this->db->query("SELECT * FROM wallposts WHERE idwallPosts < '$id' ORDER BY idwallPosts DESC LIMIT 9");
    
        $idwallPosts = array();
        foreach($result->result() as $row)
        {
            $idwallPosts[] = $row->idwallPosts));
        }
    
        print json_encode(array('posts'=>$idwallPosts));
        exit;
    }
    

    在ajax调用中,将dataType:'json'添加到$.ajax的options中,成功函数中的参数数据为:

    success: function(data) {
        var div_to_append = "<div>";
    
        $.each(data.posts, function(i,post){
            div_to_append += "<p>" + post + "</p>";
        });
    
        $(div_to_append).appendTo("#morebox");        
    }
    

    【讨论】:

    • 我已经这样做了,但 idWallPosts 没有被识别。 pastebin.com/t8BF6eDk - 当我运行 code1 时,我得到了未定义。但是当我用 data.idWallPosts 替换 this.idWallPosts 时,我收到以下警报:[object Object]、[object Object]、[object Object]、[object Object]、[object Object]、[object Object]、[object Object ],[对象对象],[对象对象],。你知道如何解决这个问题吗?
    • @Michael-Grigsby 我改变了我的答案。你试过了吗?它应该工作
    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多