三生石@ 2015-10-08 06:25 采纳率: 100%
浏览 5

Ajax分页Laravel 5.1

I'm trying to make a pagination with ajax and laravel 5, but I can not do the ajax works even with simple tests:

$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
         e.preventDefault();
            $.ajax({
          type: "GET",
          url: 'testeserver.php',
         //url:"raphael.dev/testeserver.php",
         dataType: 'json', // Notice! JSONP <-- P (lowercase)
         success:function(json){

             alert("Success"+json);
         },
         error:function(){
             alert("Error");
         }      
      });
    });
});

In this example I try one have a return on json ,

  <?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>

but only with the error alert , in fact I'm trying with these following cases :

BlogController:

  public function index(Request $request){
          $artigos = Artigo::where('publicado_em', '<=', Carbon::now())
            ->orderBy('publicado_em', 'desc')
            ->paginate(config('blog.artigos_por_pagina'));


        if ($request->ajax()) {
            return Response::json(view('Blog.artigos', compact('artigos'))->render());
        }
        return view('Blog.index', compact('artigos'));
    }

routes.php

post('/', 'BlogController@index');
get('/', 'BlogController@index');
get('/{slug}', 'BlogController@show');

jquery

$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
         e.preventDefault();
            $.ajax({
          type: "POST",
          url: 'page=' + page,
         dataType: 'json',
         success:function(json){

             alert("Success"+json);
         },
         error:function(){
             alert("Error");
         }      
      });
    });
});
  • 写回答

2条回答 默认 最新

  • weixin_33721344 2015-10-08 14:41
    关注

    Laravel protects your application with CSRF tokens. When utilising Ajax you need to be sure to send across the CSRF token, otherwise Laravel will not process the request to protect your app.

    $.ajax({
        url: 'test',
        type: "post",
        data: {'_token': $('input[name=_token]').val()},
        success: function (data) {
            alert('the joys'); 
        },
        complete: function (data) {
    
        }
    });
    

    Notice the $('input[name=_token]').val() - that will send your CSRF token. You will of course need to create a hidden input with the CSRF token in your view.

    More information can be found here!

    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入