Jquery不能在函数内部工作

Jquery get not working from inside a function

本文关键字:内部 工作 函数 不能 Jquery      更新时间:2023-09-26

所以我有以下功能:

$('#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);
  });

当下拉选项发生变化时,它会发出get请求。这是因为如果您更换您的技术人员,预约时间将会改变。这段代码给出了以下响应:

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

最重要的是,没有回复文本。现在在chrome开发工具的页面上运行这段代码:

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似乎甚至没有正确地触发?

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)
});