我怎样才能把 ajax 放在全局 js 中?

How can I put ajax in global js?

我的看法是这样的:

<input type="file" style="display: none" id="test">

文件调用时,会调用ajax

我把我的 ajax 放在 main.js (myshop\resources\assets\js\main.js)

是全局js。我把我所有的js都放在那里。我也把我的 ajax 放在那里

我把我的 ajax 放在 main.js 中,像这样:

var _token = $('input[name="_token"]').val();
console.log(_token);
$('#test').on("change", function(){ 
    data = new FormData();
    $.ajax({
        url: window.Laravel.baseUrl+'/product/addImage',
        type: "POST",
        data: { data: data, _token: _token },
        enctype: 'multipart/form-data',
        processData: false,  // tell jQuery not to process the data
        contentType: false   // tell jQuery not to set contentType
    }).done(function(data) {
        console.log(data);
    });
});

我的路线是这样的:

Route::post('product/addImage', 'ProductController@addImage');

我的控制器是这样的:

public function addImage(Request $request)
{ 
    dd('test');
    // dd($request->all());
}

执行时,控制台选项卡存在如下错误:

POST http://myshop.dev/product/addImage 500 (Internal Server Error)

并且在网络选项卡上存在这样的错误:

TokenMismatchException in VerifyCsrfToken.php line 68:

如何解决错误?

是否ajax可以放在全局js中?

您可以通过两种方式解决此问题:

你可以使用

<meta name="csrf-token" content="{{ csrf_token() }}" /> // add this under head tag
And before Ajax call add this:-
$.ajaxSetup({
    headers:
    {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

或者另一种(更简单的)方式,在你的 app\Http\Middleware/VerifyCsrfToken.php 中添加

protected $except = [
    'product/addImage',
];

希望对您有所帮助!

记得将文件添加到数据

data = new FormData();
data.append("test", $("#fileInput")[0].files[0])