javascript 在json中发送编码响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7294830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:37:58  来源:igfitidea点击:

Sending encoding response in json

phpjavascriptjqueryjson

提问by MrFoh

I am using a lot of jQuery in a project am working on.

我在一个正在处理的项目中使用了很多 jQuery。

I have a javascript function that makes an ajax request to a controller which returns data in JSON.

我有一个 javascript 函数,它向控制器发出 ajax 请求,该控制器以 JSON 格式返回数据。

I would like to display a user friendly message informing the user that he/she has no information stored yet. But I'm confused as to how to send a response in JSON so my javascript function can determine whether the user has information to be displayed.

我想显示一条用户友好的消息,通知用户他/她尚未存储任何信息。但我对如何以 JSON 发送响应感到困惑,以便我的 javascript 函数可以确定用户是否有要显示的信息。

Here is my javascript function:

这是我的 javascript 函数:

function latest_pheeds() {
    var action = url+"pheeds/latest_pheeds";
    $('#pheed-stream').html('<div class="loading"></div>');
    $('.loading').append('<img src="'+pheed_loader_src+'" />');
    $.ajax({
        url:action,
        type:'GET',
        dataType:'json',
        error: function () {
        },
        success:function(data) {
            $('.loading').fadeOut('slow');
            $.each(data,function(index,item) {
            $('#pheed-stream').append
            (
            '<div class="pheed" id="'+item.pheed_id+'">'+
            '<p><a class="user_trigger" href="users/info/'+item.user_id+'">'
            +item.user_id+'</a></p>'+
            '<p>'+item.pheed+'</p>'+
            '<div class="pheed_meta">'+
            '<span>'+item.datetime+' Ago</span>'+
            '<span class="cm">'+item.comments+
            '<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
            '</span>'+
            '<span>'+item.repheeds+
            ' Repheeds'+
            '<img class="repheed_trigger" src="/pheedbak/assets/img/communication.png" title="Click to repheed" onclick="repheed('+item.pheed_id+')">'+
            '</span>'+
            '<span>'+
            'Favourite'+
            '<img class="favourite_trigger" src="/pheedbak/assets/img/star.png" title="Click to make this a favourite" onclick="favourite_pheed('+item.pheed_id+')" />'+
            '</span>'+
            '</div>'+
            '</div>'
            );
        });
        }
    });
}

And heres the controller function the ajax request is made to

这里是控制器功能 ajax 请求

function latest_pheeds() {
    //Confirm if a user is logged before allowing access
    if($this->isLogged() == true) {
        //load the pheed model for database interaction
        $this->load->model('pheed_model');
        //load user model
        $this->load->model('user_model');
        //load comment model
        $this->load->model('comment_model');
        //store the pheeds to a the $data variable
        $data = $this->pheed_model->get_latest_pheeds();
        //Load the date helper to calculate time difference between post time and current time
        $this->load->helper('date');
        //Current time(unix timetamp)
        $time = time();
        //pheeds
        $pheeds = array();
        if(count($data) > 0 ) {
            foreach($data as $pheed) {
                $row['pheed_id'] = $pheed->pheed_id;
                $row['user_id'] = $this->user_model->return_username($pheed->user_id);
                $row['pheed'] = $pheed->pheed;
                $row['datetime'] = timespan($pheed->datetime,$time);
                $row['comments'] = $this->comment_model->count_comments($pheed->pheed_id);
                $row['repheeds'] = $pheed->repheeds;
                $pheeds[] = $row;
            }

            echo json_encode($pheeds);
            $response['response'] = "Ok";
            $res[] = $response;
            echo json_encode($res)."\n";
        }
    } else {

    }

It generates the JSON output,but the syntax is broken so i cant read it with javascript, but once i get rid of the following code from the above method it works normally

它生成 JSON 输出,但语法已损坏,因此我无法使用 javascript 读取它,但是一旦我从上述方法中删除了以下代码,它就可以正常工作

  $response['response'] = "Ok";
  $res[] = $response;
  echo json_encode($res)."\n";

回答by Andreas

You MUST only use json_encode($data) once in a response, if you want to output more stuff, you need to merge your data into one array and send that.

您只能在响应中使用 json_encode($data) 一次,如果您想输出更多内容,则需要将数据合并到一个数组中并发送。

EDIT: To be clear, one way you could do it is like this:

编辑:要清楚,你可以这样做的一种方法是这样的:

echo json_encode(array('pheeds' => $pheeds, 'res' => $res));

Then in JS you will get an array with the keys "pheeds" and "res".

然后在 JS 中,您将获得一个带有“pheeds”和“res”键的数组。

Although it may be of little practical significance, I would also recommend doing this before you echo the json encoded string:

虽然它可能没有什么实际意义,但我也建议您在回显 json 编码字符串之前执行此操作:

header('Content-Type: application/json');