我正在使用 jQuery 和 Ajax 在 laravel 中制作國家和城市的依賴下拉串列。我在 localhost Xampp 上做。首先,我將 jQuery 用于國家/地區。當國家/地區更改 jQuery 獲取值并發送到控制器。但是當我將值從 RegistrationFormComponent 發送到 CountryStateCity 控制器并嘗試顯示我得到的值時。我收到一個錯誤( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) )。我不知道為什么我會收到這個錯誤。
路線:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
jQuery 和 Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
控制器
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
我想我嘗試了所有可能的事情。但是沒有用。請告訴我如何才能擺脫這個問題。還請告訴我如何使用 jquery 和 ajax 將資料從組件發送到控制器并獲取值表單控制器并從資料庫中獲取資料并發送回組件。
uj5u.com熱心網友回復:
這個寫錯了。
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
它應該看起來像這樣。
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
uj5u.com熱心網友回復:
請檢查控制器功能
公共函式getstate(請求$請求){
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/521582.html
