【问题标题】:unable to return data from controller to ajax无法将数据从控制器返回到 ajax
【发布时间】:2017-12-23 20:39:34
【问题描述】:

我正在使用 phalcon 框架,在我的博客中,我想用 ajax 附加 cmets,但问题出在我的控制器查询中。我不明白如何返回查询数据以使用 ajax 查看。我当前的查询脚本返回整个洞 html 页面,但我只需要注释数据。有人请帮忙

[控制器]

public function detailsAction($id)
{
    $blog = Blogs::findFirstByid($id);

#Comments Retrieve
    $coment = Comments::find();
}

public function bCommentAction()
{
    if($this->session->has('uname'))
    {
        if($this->request->isPost() == true || $this->request->isAjax() == true) 
        {
            $comments = new Comments();
            $comments->cauthor = trim($this->session->get('uname'));
            $comments->bcoment = trim($this->request->getPost('bComent'));
            $comments->entry_id = trim($this->request->getPost('postId'));
            if(!$comments->create() == true)
            {
                $this->flashSession->success("SUCCESS:: Comments inserted");
                return $this->response->redirect($this->request->getHTTPReferer());
            }
            else
            {
    return $this->response->setJsonContent(['bcoment' => $comments->bcoment, 
    'cauthor' => $comments->cauthor, 'entry_id' => $comments->entry_id]);
            }
        }
        else{echo('Request is Not ajax!');}
    }
    else
    {
        echo('<script>alert("You are not loggedin!");</script>');
    }
    $this->view->disabled();
}

[Jquery]

$('#blogComment').submit(function(e){
    e.preventDefault();
    var blogComent = $("input[name='bComent']").val();
    var postsId = $("input[name='idPost']").val();
    $.ajax({
        url:'blog/bComment/',
        type: 'POST',
        cache: false,
        data: {'postId':postsId,'bComent':blogComent},
        success: function(data){ 
            $('#datax').append('<div class="bcom">'+json.stringify(data)+'</div>').fadeIn(500);
        }
    });
    return false;
});

[查看]

<div id="datax">
{% for coment in comented %}
{% if coment.entry_id === detail.id %}
<div class="bcom">
{% for user in logged %}
{% if coment.cauthor === user.uname %}
{{ image('data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=',"alt": "Some Photo","data-src":"uploads/users/"~user.image,"title":""~user.uname,"class":"comentedId") }}
{% endif %}
{% endfor %}
<b>{{coment.cauthor}}</b><br/>
{{coment.bcoment}}
</div>
{% endif %}
{% endfor %}</div>

输出如下图所示:

【问题讨论】:

  • 你能用当前的 HTML 标记更新你的问题吗?想要的结果,好吗?
  • 只检查成功回调中返回的数据是什么。不确定这里到底发生了什么。您确定数据是此回调中的对象吗?

标签: javascript php jquery ajax phalcon


【解决方案1】:

您只能获取评论的文本并将其“回显”为 json 文件。对从服务器返回 json 进行研究。互联网上有很多关于如何将 php 数组解析为 json 字符串并为 ajax 请求检索它的参考资料。

而且,您还必须更改 javascript 的 ajax 请求,以便获取该 json 字符串并将其解析为 javascript 数组。

【讨论】:

  • 你能举个例子吗?
  • 我明白你在做什么。而不是在这里重定向: return $this->response->redirect($this->request->getHTTPReferer());你只需要显示数据。你能显示方法“$cmets->create()”吗?
  • 在您的 php 脚本中,您必须返回包含数据的 json 字符串。我会找到一个例子。
  • 如果我喜欢:返回 json_encode($cmets);然后输出如下: [object object] 在刷新洞页面后立即显示真实数据
  • 像这样:你做你的 mysql 查询......然后你有一个看起来像这样的数组,我想: $row = ("username"=> "John", "content" =>“这是我的评论”)。只需: header('Content-type: application/json'); echo json_encode($row);
【解决方案2】:

尝试将此行移到操作的顶部。:

$this->view->disabled();

从你当前的代码来看,它永远不会被触发。

另外,我会考虑重写这个块:

    if(!$comments->create() == true)
    {
        $this->flashSession->success("SUCCESS:: Comments inserted");
        return $this->response->redirect($this->request->getHTTPReferer());
    }
    else
    {
        return $this->response->setJsonContent(['bcoment' => $comments->bcoment, 'cauthor' => $comments->cauthor, 'entry_id' => $comments->entry_id]);
    }

也许像这样简单:

if(!$comments->create()){
    return $this->response->setJsonContent(['status' => 'error']);
) else {
    return $this->response->setJsonContent([
        'status' => 'success',
        'payload' => [
            'bcoment' => $comments->bcoment, 
            'cauthor' => $comments->cauthor, 
            'entry_id' => $comments->entry_id
        ]
    ]);
}

【讨论】:

    【解决方案3】:

    试试这样:

    $('#comentSave').on('click', function(e) {
        e.preventDefault();
        var coment = $('.comnt').val();
        var cid = $('.pid').val();
        $.ajax({
        type:'POST',
        url:'blog/comments',
        data:{'bcoment':coment,'postId':cid},
        beforeSend: function(){$('.loader').html('Processing...');}
        }).done(function(resp){
            console.log(typeof resp);
            resp = JSON.parse(resp);
            resp.forEach(function(value){
                if(value.e === 'e1'){alert('Insertion Failed!');}
                if(value.e === 'e2'){alert('You are not authorized!');}
                if(value.e === 'e3'){if(value.uname === value.cauthor){var cdata = 'bcomBase';}else{cdata = 'bcom';}
                    $('#datax').append('<div class="'+cdata+'"><img src="uploads/users/'+value.userimg+'"><b>'+value.cauthor+'</b><br/>'+value.bcoment+'</div>');
                    $('.comentcount').text(value.count);
                }
            });
            $('#blogComment')[0].reset() || $('.comnt').val('');
        }).fail(function(){ alert('Reload & try again..!'); }).always(function(){});
        return false;
    });
    
    
    public function commentsAction()
    {
    $this->view->disable();
    if(!empty($this->session->get('uname')))
    {
        $comments = new Comments();
        $comments->cauthor = $this->session->get('uname');
        $comments->bcoment = $this->request->getPost('bcoment');
        $comments->entry_id = $this->request->getPost('postId');
        $resData = array();
        if($comments->save() === true)
        {
            $data = Blogs::findFirstByid($this->request->getPost('postId'));
            $cc = Comments::countByentry_id($this->request->getPost('postId'));
            $user = Users::findFirstByid($this->session->get('id'));
            $query = Comments::findByid($comments->id);
            foreach($query as $q){$resData[] = array('bcoment' => $q->bcoment, 'cauthor' => $q->cauthor, 'entry_id' => $q->entry_id, 'count' => $cc, 'userimg' => $user->image, 'e' => 'e3', 'uname' => $data->blog_author);}
            echo(json_encode($resData));                
        }
        else{$resData[] = array('e' => 'e1');echo(json_encode($resData));}
    }
    else{$resData[] = array('e' => 'e2');echo(json_encode($resData));}
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      相关资源
      最近更新 更多