Pregunta

I need to run multiple $.get functions to several different php scripts and I was wondering if I can do it all in one generic function and just return the data. My plan was to do something like:

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

However, this does not work because it is in a nested function. Is this possible (easily) or am I going to have to do the $.get one at a time?

¿Fue útil?

Solución

Remember that in Javascript functions are first class citizens, so rather than return a value, you would probably do best sending a function:

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

This is a poor example since it does not handle exceptions etc. But it should give you an idea on the flexibility provided to you. The key is to remember that functions are the building block of the language and what gives it power.

If you really want to stick with the method you are using (I don't recommend), you could add one additional function... (I really really don't recommend).

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

Doing this would result in you losing the ability to change how the experience is handled based on the call result. Perhaps you want a select box disabled until the call completes and it is populated or perhaps you want to perform something special when a call fails. Using functions are a better approach.

Hope this helps.

Otros consejos

If you are using jquery 1.5, $.get will return a jqXhr object, which implements the promise interface:

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise

Which can be used like this:

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
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top