【发布时间】:2017-06-15 12:55:58
【问题描述】:
我是 ajax 新手。 我想从 ajax 响应中填充下拉列表。 响应是一个医生的 json,我想用这个列表填充一个下拉列表,以便管理员可以为患者选择一个特定的医生。
这是我的 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: "doctor@gerocare.org"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: "doctor@gerocare.orgj"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元素。如果您想要更具体的示例,请发布实际的result内容。 -
好的,我刚刚添加了 json 结果...@RoryMcCrossan