tags:

views:

38

answers:

1

Is there a better to write the following?

I have two services that I need to call.

The data returned from the first service is needed to create the url for the second ajax call.

    $.ajax({
     url: 'http://service',
     type: 'GET',
     dataType: 'json',
     timeout: 1000,
     error: function(){
      alert('Error loading json document');
     },
     success: function(json){
      processJson(json.foo);
     }
    });


    function processJson(url) {

    $.ajax({
     url: url,
     type: 'GET',
     dataType: 'json',
     timeout: 1000,
     error: function(){
      alert('Error loading json document');
     },
     success: function(json){
             displayJson(json.foo);
     }
    });
}
+3  A: 

nope, thats how I would do it. Maybe I'd use some of the built inn ajax functions, or create a function with those parameters preset:

function ajax(url, error, success){
  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    timeout: 1000,
    error: function(){
      alert('Error loading json document');
    },
    success: success,
  });
}


ajax('http://service', function(json){
  ajax(json.foo, function(json){
    displayJson(json.foo);
  });
});
Marius
+1 That's a reasonably elegant solution.
cletus