阿贾克斯不会在laravel工作

时间:2017-03-15 07:29:10

标签: php laravel-5.1

ajax在laravel工作

View/message.php 
<html>
<head>
  <title>Ajax Example</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


  <script type="application/javascript">
     function getMessage(){
        $.ajax({
           type:'POST',
           url:'/getmsg',
           data:'_token = {{ csrf_token() }}',         dataType: 'json',
           success:function(data){
              $("#msg").html(data.msg);
           }
        });
     }
  </script>

  <div id = 'msg'>This message will be replaced using Ajax. 
     Click the button to replace the message.</div>     

  <?php
     echo Form::button('Replace Message',['onClick'=>'getMessage()']);
  ?>

在上面的代码中,我只需单击按钮(替换消息)并调用ajax

Routes.php

Route::get('/ajax',function(){
return view('message');
});
Route::post('/getmsg','AjaxController@index');

AjaxController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use ajax;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AjaxController extends Controller {
public function index(){
  $msg = "This is a simple message.";
  return response()->json(array('msg'=> $msg), 200);
}
}

但它不起作用 它显示出一些像这样的错误 POST http://localhost:8000/getmsg 500(内部服务器错误)

Tutorial link

1 个答案:

答案 0 :(得分:1)

通过改变代码来解决问题...... 数据:{&#39; _token&#39; :&#39; {{csrf_token()}}&#39;}