Jquery无法在函数内部工作

时间:2014-08-11 22:16:32

标签: javascript jquery

所以我有以下功能:

$('#calendar_appointment_technician_id').change(function(){
    var technician = $('#calendar_appointment_technician_id').val();
    var date = $('#date').val();
    var id = $('#calendar_appointment_id').data("id");
    var response = $.get("/update_appointment_times?technician="+technician+"&date="+date+"&id="+id);
    $('#appointment_times').html(response.responseText);
  });

选项下拉列表更改时获取请求的内容。这是因为如果您更换技术人员,预约时间将会改变。此代码给出以下响应:

Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

最重要的是,没有回复文字。现在在页面上的chrome dev工具中运行此代码:

var technician = $('#calendar_appointment_technician_id').val();
    var date = $('#date').val();
    var id = $('#calendar_appointment_id').data("id");
    var response = $.get("/update_appointment_times?technician="+technician+"&date="+date+"&id="+id);
    $('#appointment_times').html(response.responseText);

该代码为我提供了一个响应文本,响应如下:

Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

为什么这个功能在函数之外工作正常但是从get中看起来似乎没有正常触发?

1 个答案:

答案 0 :(得分:3)

jQuery的.get()方法是异步的,你需要确保它在尝试使用返回数据之前已经完成。

$.get()返回一个jQuery.promise接口,我们可以在get请求完成时使用它。

var response = $.get("/update_appointment_times?technician=" + technician + "&date=" + date + "&id=" + id);

response.then(function (response) {
    $('#appointment_times').html(response)
});