首页 > 解决方案 > 我无法从 jQuery Ajax 提交 Laravel 5.7 获取数据

问题描述

帮助我,我正在尝试在 laravel 5.7 中通过邮寄方式接收来自 jQuery ajax 提交的数据。但是我做不到TT。我总是在控制器中一无所获。我也尝试在 laravel 文档和其他网站上找到它。但我找不到任何解决方案。这是我的代码。

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OrderController;

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

Route::get('ajax', function(){
    return view("wash");
});
Route::post('getmsg', 'AjaxController@index');
<?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);
    }
}
<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>

标签: laravel-5.7

解决方案


推荐阅读