我无法从jQuery Ajax提交数据提交Laravel 5.7

时间:2019-01-30 02:18:18

标签: laravel-5.7

帮帮我,我试图从laravel 5.7中的post by jQuery ajax接收数据。但我无法做到这一点。我在控制器中一无所获。而且我还尝试在laravel文档和其他站点上找到它。但是我找不到任何解决方案。 这是我的代码。

  • 路线(web.php)
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OrderController;

Route::get('ajax', function(){
    return view("wash");
});
Route::post('getmsg', 'AjaxController@index');
  • 路线(web.php)
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OrderController;

Route::get('ajax', function(){
    return view("wash");
});
Route::post('getmsg', 'AjaxController@index');
  • 控制器(AjaxController.php)
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AjaxController extends Controller{
    public function index(Request $request)
    {
        $id =  $request->input('id');

        $msg = "This is a simple message ".$id;
        return response()->json(array("msg"=>$msg), 200);
    }
}
  • 查看(wash.blade.php)
<html>
   <head>
      <title>Ajax Example</title>
      <meta name="csrf-token" content="{{ csrf_token() }}">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      </script>

      <script>
         function getMessage() {
             var dataString = { 
                     id : $(this).attr('id')
                   };

             $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
               $.ajax({
                   type: "POST",
                   url: "{{ URL::to('getmsg') }}",
                   data: dataString,
                   dataType: "json",
                   cache : false,
                   success: function(data){
                       $("#msg").html(data.msg);
                   }
                });
         }
      </script>
   </head>

   <body>
          <div id = 'msg'>
              <p>This message will be replaced using Ajax.</p> 
              <p>Click the button to replace the message.</p>
          </div>
      <?php
         echo Form::button('Replace Message',['onClick'=>'getMessage()']);
      ?>
   </body>

</html>

0 个答案:

没有答案