如何在SilexInsert文章中使用jQueryajax



我正试图在数据库中进行一些插入,然后查看帖子列表通过ajax显示它,但我不太确定如何做到。

这是我的路线:

$app->match('/status', 'PostStatusPostControllerStatusPostController::statusAction')->bind('main');

然后在我的控制器上,我处理插入的东西,然后访问Model实体并将其传递到视图

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

然后在我看来,只有一个简单的文本区域。因此,在提交帖子时,它应该通过ajax 显示

这是我的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);
}); 

});

但提交后什么也没发生。

看起来你说的是GetJSON,但你发送的是Html?无法工作。您应该发送JsonResponse,或者必须正确设置Headers"Content-Type:application/json"。如果使用GetJSON,浏览器会尝试自动转换php脚本中的响应(无论其silex是否为),并且标头必须为JSON类型。

最新更新