如何在ajax中显示请求后的结果

how to display result after requst in ajax

本文关键字:请求 结果 显示 ajax      更新时间:2023-09-26

我如何在ajax成功中显示我的结果,以便它显示返回结果而不重新加载页面。

这是我的脚本——

  <script>
    $(document).ready(function () {
        $("#searchform").on('submit', function (e) {
            $.ajax({
                url: '/home',
                type: 'post',
                data: {contentSearch: $('#contentSearch').val()},
                success: function (data) {
                    $('table.my-data-table').dataTable({}) // the table
                     // here i want to show the result
                     // how can i show the result here
                     // i am passing the result as result in the twig file
                }
            });
            return false;
        });
    });
</script> 

在控制器中,我发送的结果像'result' => $result

return $this->render('AdminBundle:Home:home.html.twig', array(
        'pageTitle' => 'my ajax',
        'result' => $result // result sending to twig file
            )

那么我如何通过ajax显示结果,谁都知道如何解决这个问题。

使用event.preventDefault()来阻止默认操作,这样页面就不会重新加载。

$("#searchform").on('submit', function (event) {
   event.preventDefault();
   // ...
});

如果你正在接收一个包含表数据的数据数组,那么将它传递给dataTable的data属性:

   success: function (data) {
     $('table.my-data-table').dataTable({
       data: data
     });
   }