简体   繁体   English

如何在Silex插入帖子中使用jQuery Ajax

[英]How to use jQuery ajax in Silex Insert post

I'm trying to do some insert into the database then view the post list and display it by ajax, but i'm not pretty sure how to do it. 我正在尝试插入数据库然后查看帖子列表并通过ajax显示它,但我不确定如何做到这一点。

Here's my route: 这是我的路线:

$app->match('/status', 'Post\StatusPost\Controller\StatusPostController::statusAction')->bind('main');

Then on my controller I process the insert stuffs then access the Model entity and pass it into the view 然后在我的控制器上处理插入的东西,然后访问Model实体并将其传递给视图

$posts = new Post();
$posts = $posts->allPosts($app);

return $app['twig']->render('status.html.twig', [
  'form' => $form->createView(),
  'posts' => $app->json($posts),
]);

Then on my view there's just a simple text area. 在我看来,只有一个简单的文本区域。 So upon submitting the post it should display it via ajax 因此,提交帖子后,它应该通过ajax显示

Here's my js script 这是我的js脚本

$('#status-btn').click(function(){
$.getJSON('/status', function(data){
  console.log(data);
  var html;
  $.each(data, function(entryIndex, entry){
    html += '<div class="status-container">';
    html += '<h3 class="status-title">' + entry.name + '</h3>';
    html += '<img src="' + window.location.href + '/images/' + entry.image + '">';
    html += '<p class="status-content">' + entry.status + '</p>';
    html += '<span class="status-time">' + entry.timestamp + '</p>';
    html += '</div>';
  });
  $('.content-container').html(html);
}); 

}); });

But upon submitting it nothing happens. 但是提交后什么也没有发生。

It looks like that you say GetJSON, but you send Html? 看起来你说GetJSON,但你发送Html? cannot work. 无法工作。 you should send a JsonResponse or you must set the Headers properly 'Content-Type: application/json'. 您应该发送一个JsonResponse,或者必须正确设置Headers'Content-Type:application / json'。 If you use GetJSON the browser tries automatically convert the response from the php script (no matter if its silex) and the header must be of type JSON. 如果您使用GetJSON,浏览器将尝试自动转换来自php脚本的响应(无论是否为silex),并且标头必须为JSON类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM