无法将数据从控制器返回到ajax

时间:2017-07-18 19:55:07

标签: javascript php jquery ajax phalcon

我正在使用phalcon框架,在我的博客中,我想用ajax附加注释,但问题出在我的控制器查询中。我不明白如何使用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>

输出如下图所示:

enter image description here

3 个答案:

答案 0 :(得分:0)

尝试将此行移至行动的顶部。:

$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
        ]
    ]);
}

答案 1 :(得分:0)

尝试这样:

$('#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));}
}

答案 2 :(得分:-1)

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

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