如何从ajax响应中填充下拉选项

时间:2017-06-15 12:55:58

标签: jquery ajax laravel

我是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

3 个答案:

答案 0 :(得分:2)

首先尝试验证你的医生模型是否返回了一些东西,然后像这样返回:

return response()->json($doctors);

json响应将在对象数组中格式化输出对象。

现在你可以像下面的例子一样填充你的组合框。

$("button").click(function(e) {
e.preventDefault();
var id = $(this).val();
var select = $('#YourSelectBoxID');
$.ajax({

type: "POST",
    url: "map/"+id,
    data: { 
        id: $(this).val(),
        '_token': $('input[name=_token]').val() 
    },
    success: function(data) {
        var htmlOptions = [];
        if( data.length ){
              for( item in data ) {
                  html = '<option value="' + data[item].id + '">' + data[item].firstname + '</option>';
              htmlOptions[htmlOptions.length] = html;
              }

              // here you will empty the pre-existing data from you selectbox and will append the htmlOption created in the loop result
              select.empty().append( htmlOptions.join('') );
          }
    },
    error: function(error) {
        alert(error.responseJSON.message);
    }
})

});

祝你好运!

答案 1 :(得分:0)

找到您想要填充的选择元素:

M 173600704 173600080 leo/core/commit_timestamp.json
M 173600368 173599408 leo/core/leoTest.py
M 173600272 173598928 leo/test/unitTest.leo

然后在ajax成功函数中,迭代结果并将它们附加为html:

var el = $('select[name="doctors"]');

至少会产生这种效果。

答案 2 :(得分:0)

这是一个简单的例子,取决于它将改变的确切响应:

  $("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) {
            var toAppend='<option value="null">default</option>>'
            for(var obj in result){
                toAppend+='<option value="'+obj.id+'">'+ obj.title +'</option>>'
            }

            $("#populated").append(toAppend)
        }
        },
        error: function(result) {
            alert('error');
        }
    });

这是html输入:

<select id="populated"></select>