我对 Laravel 很陌生。
我想将 ajax 调用中的两个变量传递给类中的方法。
我的 ajax 调用(来自各种 Google 搜索)是:
var token = $('meta[name="csrf-token"]').attr('content');
var inputValue = "Testing";
var anotherInput = "Testing2";
var data = {};
data.anotherInput = anotherInput;
data.inputValue = inputValue;
data._method = 'POST';
data._token = token;
//data: JSON.stringify(data),
$.ajax({
url: postUrl,
type: 'POST',
headers: {
'X-CSRF-TOKEN': token
},
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: false,
success:function(response)
{
console.log(response);
},
error: function(response) {
console.log(response);
}
});
var“postUrl”在我的layout.blade.php中设置:
<script>
var postUrl = "{{ route('filepathtest') }}";
</script>
我的控制器类的顶部是:
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
// use Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Response;
use App\Models\MainSettings;
use App\Http\Requests\MainSettingsRequest;
class MainSettingsController extends Controller
{
private string $messageTitle = "";
private $messageText = array();
/**
* Corrects path and checks it points to something.
*/
public function filePathTest(Request $request)
{
$data = $request->all();
$response = array(
'msg' => $data,
);
return response()->json($response);
}
最后,我的路线是:
Route::match(array('GET','POST'),'filepathtest', [MainSettingsController::class, 'filePathTest'])->name('filepathtest');
我的响应被记录到 Console.Log 中,我看到以下内容:
我尝试了很多从控制器访问变量的方法,但无济于事?
我试过了:
$data = $request->input('anotherInput');
And:
$data = $request->anotherInput;
And:
$data = $request['anotherInput'];
And:
$data = $request->post('anotherInput');
And:
$data = $request->request('anotherInput');
但除了最后一个给我一个错误之外,它们似乎都返回 null (除非我只是在顶部“use Request;”而不是“use Illuminate\Http\Request;”)?