JQuery:什么'这两个$.get()方法之间的区别是什么

JQuery: what's the difference between these two $.get() methods?

本文关键字:两个 get 之间 是什么 区别 方法 什么 JQuery      更新时间:2023-11-13

服务器:

def csv_data(request): #mapped to url /csv_data
    with open('my_static_data.csv', 'r') as csv:
        response = HttpResponse(csv.read(), content_type="text/csv")
        response['Content-Disposition'] = 'attachment; filename="data.csv"'
    return response #returns the csv file

客户端:

1.

function csv_data() {
  var response = $.get('/csv_data');
  return response;
}
$(function () {
  var my_data = csv_data();
  console.log(my_data); //returns a response object
  console.log(my_data.responseText); //undefined?!
}

2.

$(function () {
  $.get('/csv_data', function(d) {
    console.log(d); // returns csv_data. Why not the same response object?
  });
}

方法#2返回的数据就是我想要使用的。为什么my_data.responseText是undefined,为什么这两个方法返回不同的对象?

$.get不是重载的jQuery函数;为了方便起见,它只是返回异步请求对象,尽管该对象存在,但其响应尚未填充。您仍然需要使用回调来使用结果:

function csv_data(callback) {
  $.get('/csv_data', callback);
}
$(function () {
  csv_data(function(my_data) {
    console.log(my_data); // returns a response object
    console.log(my_data.responseText); // not undefined
  });
});

第一个返回一个延迟对象。

function csv_data() {
   return $.get('/csv_data');
}
csv_data().done(function(my_data) {
    console.log(my_data);
});

只是管理回调的另一种方式。

因此,不管怎样,数据都是通过回调访问的。只是在第一个示例中,您可以通过返回的对象来分配它,在第二个示例中它作为参数分配给$.get()

来自文档:

从jQuery 1.5开始,jQuery的所有Ajax方法都返回一个超集XMLHTTPRequest对象。此jQuery XHR对象或"jqXHR"$.get()返回的函数实现了Promise接口Promise的属性、方法和行为(请参阅递延对象以获取更多信息)。

因此,此代码中的response不是AJAX请求的实际数据:

var response = $.get('/csv_data');

然而,这里d是AJAX请求的数据响应:

$(function () {
  $.get('/csv_data', function(d) {
    console.log(d); // returns csv_data. Why not the same response object?
  });
}

因为默认情况下请求是异步的。在第一种情况下,您希望在请求启动后立即使用结果。在第二个例子中,您定义了一个回调,只有在请求完成后才会调用它。