我是新來的ajax。 我想從ajax響應中填充下拉列表。 反應是醫生得到的json,我想用這個列表填充下拉列表,以便管理員可以爲患者選擇特定的醫生。如何從ajax響應填充下拉選項
這裏是我的Ajax代碼:
$("button").click(function(e) {
e.preventDefault();
var id = $(this).val();
$.ajax({
type: "POST",
url: "map/"+id,
data: {
id: $(this).val(),
'_token': $('input[name=_token]').val()
},
success: function(result) {
console.log(result);
},
error: function(result) {
alert('error');
}
});
PS:我使用的console.log,所以我可以查看結果
和我laravel控制器的方法:
public function getDoctorSuggests(Request $request){
$id = $request->id;
// Get id from database, just skiping this step there
$patient = Patient::find($id);
if ($patient instanceof Patient){
//get patient location details
$city = $patient->city;
//get doctors
$doctors = Doctor::where('city', $city)->get(); //narrow search to city
if (!$doctors->isEmpty()){
$distance =[];
foreach($doctors as $doctor){
$location = $this->distance($patient->latitude, $patient->longitude, $doctor->latitude, $doctor->longitude, 'K');
array_push($distance, $location);
}
return response()->json(['doctors' => $doctors]);
}
return response()->json(['doctors' => NULL]);
}
}
請我該怎麼辦得到結果,並填寫一個html下拉菜單,而無需重新加載頁面?
JSON響應是(從我的Chrome檢查控制檯得到)
Object {doctors: Array(2)}doctors: Array(2)0: Objectaddress: "29 Mambilla Street, Abuja, Nigeria"age: 2city: "Abuja"country: "Nigeria"created_at: "2017-06-14 01:01:06"currency: nulldoctor_cv: nulldoctor_mdcn: "wwjdnwe"email: "[email protected]"firstname: "Doctor"id: 1lastname: "Doctor"latitude: 9.0805515longitude: 7.5098858midname: "Midname"phone: "9"place_id: "ChIJ2fEzeToKThARPnGlvU-PKh0"sex: 2state: "FCT"updated_at: "2017-06-14 01:08:52"zip_code: null__proto__: Object1: Objectaddress: "29 Mambilla Street, Abuja, Nigeria"age: 2city: "Abuja"country: "Nigeria"created_at: "2017-06-14 01:01:06"currency: nulldoctor_cv: nulldoctor_mdcn: "wwjdnwe"email: "[email protected]"firstname: "Doctor"id: 3lastname: "Doctor"latitude: 9.0805515longitude: 7.5098858midname: "Midname"phone: "9"place_id: "ChIJ2fEzeToKThARPnGlvU-PKh0"sex: 2state: "FCT"updated_at: "2017-06-14 01:08:52"zip_code: null__proto__: Objectlength: 2__proto__: Array(0)__proto__: Object
根據需要遍歷'result'和'append()'新的'option'元素。如果您想要更具體的示例,請發佈實際的「結果」內容。 –
好的,我只是添加了json結果... @RoryMcCrossan –