-1

I have the jquery json request in the following format:

JSON request:

$.getJSON('http://xyz.com',function(result) {});

If the request fails(server not responds), how do i redirect to another domain. for example "http://zxy.com".(we maintaining the same code in another server)

Ram
  • 143,282
  • 16
  • 168
  • 197
user655334
  • 965
  • 3
  • 15
  • 27

3 Answers3

3

I think that it may be better to use $.ajax(), error method or success if the server tells you based on the response).

Then use this to redirect the browser.

window.location = "http://www.google.com"
JoeFletch
  • 3,820
  • 1
  • 27
  • 36
2

$.getJSON() is defined as:

jQuery.getJSON=function(url,data,callback){
    return jQuery.get(url,data,callback,"json");
};

and as such, fails silently.

To react to errors you'll need to use the $.ajax() function directly which allows you to define an onError handler, as in:

$.ajax({
    url: '...',

    contentType:'json',

    success:function(result,stat,xhr){
        ...
    },

    error:function(xhr,opts,err){
        ...
    }
});

See jQuery Ajax error handling, show custom exception messages for further information.

Community
  • 1
  • 1
Rob Raisch
  • 17,040
  • 4
  • 48
  • 58
0

Did you try this?

function addImage(item) {
 $("<img/>").attr("src", item.media.m).appendTo("#images");
}

    var jqxhr = $.getJSON("http://xyz.com",function(data) {
    $.each(data.items, function(i,item){  //sample
       addImage(item);
    })
    .error(function() { 
              var jqxhrFailover = $.getJSON("http://zzz.com", function(data) {
    $.each(data.items, function(i,item){  //sample
       addImage(item);
    }).error(function(){ alert('both failed!'); });
Ram
  • 143,282
  • 16
  • 168
  • 197
turtlepick
  • 2,694
  • 23
  • 22
  • thanks, But how do i get the results from database, like "result.username" etc from the second url(if error occurs) – user655334 Sep 22 '12 at 05:05
  • You need to pass loop the values. – turtlepick Sep 22 '12 at 05:06
  • I tried to put an example above. Try to make it work for one server and then just cascade the calls on the .error() – turtlepick Sep 22 '12 at 05:08
  • Are you sure you are getting a JSON back? If you have a service endpoint it's unlikely you would get a 404. but yes, I believe it would fall in the error() block. – turtlepick Sep 22 '12 at 05:10
  • how do i check the status code in u r code. if server is down(not responding). – user655334 Sep 22 '12 at 05:14
  • Change the error handling to somethng like this: .error(function(jqXHR, textStatus, errorThrown) { console.log("error " + textStatus); console.log("incoming Text " + jqXHR.responseText); }) – turtlepick Sep 22 '12 at 05:15