weixin_33736649 2016-10-07 07:47 采纳率: 0%
浏览 37

Laravel 5中没有Ajax响应

I am trying to get an Ajax response using Laravel 5 but it just wont work. This is the error I see in the Chrome debugger:

POST http://localhost:8000/getmsg 500 (Internal Server Error)send @ jquery.min.js:4ajax @ jquery.min.js:4getMessage @ ajax:10onclick @ ajax:25

This is message.php in resources/views:

<html>
   <head>
      <title>Ajax Example</title>

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

      <script>
         function getMessage(){
            $.ajax({
               type:'POST',
               url:'/getmsg',
               data:'_token = <?php echo csrf_token() ?>',
               success:function(data){
                  $("#msg").html(data.msg);
               }
            });
         }
      </script>
   </head>

   <body>
      <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()']);
      ?>
   </body>

</html>

This is my Ajaxcontroller.php:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
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);


}
}

Then I added this to the web.php in routes:

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

4条回答 默认 最新

  • weixin_33714884 2016-10-07 07:50
    关注

    Change the url in this ajax code to the correct path (e.g //public/getmsg)

    <script>
             function getMessage(){
                $.ajax({
                   type:'POST',
                   url:'/<project_name/public/getmsg',
                   data:'_token = <?php echo csrf_token() ?>',
                   success:function(data){
                      $("#msg").html(data.msg);
                   }
                });
             }
          </script>
    
    评论

报告相同问题?