从嵌套的$.get返回值

return value from nested $.get

本文关键字:get 返回值 嵌套      更新时间:2023-09-26

我需要在几个不同的php脚本中运行多个$.get函数,我想知道是否可以在一个通用函数中完成所有操作并返回数据。我的计划是做一些类似的事情:

var companyName = 'Google';
var customers = get('Customers', companyName);
var vendors = get('Vendors', companyName);
function get(table, variable){
    $.get('http://www.mysite.com/phps/get'+table+'.php', {company: variable}, function(data){return data});
}

但是,这不起作用,因为它位于嵌套函数中。这可能(容易)吗?还是我必须一次做$.get?

请记住,在Javascript中,函数是第一类公民,因此与其返回值,不如发送一个函数:

var companyName = 'Google';
var customers, vendors;
get('Customers', companyName, function(data) { customers = data; });
get('Vendors', companyName, function(data) { vendors = data; });
function get(table, variable, success){
    $.get('http://www.mysite.com/phps/get'+table+'.php', {company: variable}, success);
}

这是一个糟糕的例子,因为它不处理异常等。但它应该让你了解提供给你的灵活性。关键是要记住,函数是语言的组成部分,是什么赋予了它力量。

如果你真的想坚持使用(我不推荐)的方法,你可以添加一个额外的函数(我真的不推荐)

var companyName = 'Google';
var customers, vendors;
get('Customers', companyName, customers);
get('Vendors', companyName, vendors);
function get(table, variable, results){
    $.get('http://www.mysite.com/phps/get'+table+'.php', {company: variable}, function(data){ results = data});
}

这样做会导致您失去根据调用结果更改体验处理方式的能力。您可能希望在调用完成并填充之前禁用一个选择框,或者您希望在调用失败时执行一些特殊的操作。使用函数是一种更好的方法。

希望这能有所帮助。

如果您使用的是jquery 1.5,$.get将返回一个jqXhr对象,它实现了promise接口:

从jQuery1.5开始,jQuery的所有Ajax方法都返回XMLHTTPRequest对象的超集。$.get()返回的这个jQuery XHR对象或"jqXHR"实现了Promise接口,为它提供了Promise 的所有属性、方法和行为

可以这样使用:

function yourMultipleGetFunction(success, error) {
    var jqXhr1 = $.get('url', data);
    var jqXhr2 = $.get('url2', data2);
    $.when(jqXhr1, jqXhr2).then(success, error);
}
yourMultipleGetFunction(function(data1, data2){
     //handle the objects returned from the get requests
}, function(jqXHR, textStatus, errorThrown){
    //something went wrong, handle the error here
});