Can I check if the URL is accessible using AJAX + cross-domain + jsonp?

I use jQuery to extract information from a url and display it on my page asynchronously. The url comes from another domain, so I use JSONP to get the data. It works great.

However, when the remote URL doesn’t work (which happens once in a while) my page freezes as JQuery AJAX does not cause a “success” or an “error”.

I am using jQuery 1.7.

My code looks like this:

$.ajax({ type : "GET", url : "http://otherdomain.com/somePage.html", data : params, dataType : "jsonp", jsonp : "jsonp", success : function (response, textS, xhr) { alert("ok"); }, error : function (xmlHttpRequest, textStatus, errorThrown) { alert("not ok " + errorThrown); } }); 

If "somePage" is raised, I see the message "ok". If "somePage" is not available, I don’t see anything.

Any ideas on how I can get the error function to be called? Or more importantly, how do you determine if cross-domain URLs are accessible?

Is it possible?

Thanks,

+6
source share
1 answer

add timeout

 $.ajax({ type : "GET", url : "http://otherdomain.com/somePage.html", data : params, timeout:3000, dataType : "jsonp", jsonp : "jsonp", success : function (response, textS, xhr) { alert("ok"); }, error : function (xmlHttpRequest, textStatus, errorThrown) { alert("not ok " + errorThrown); if(textStatus==='timeout') alert("request timed out"); } }); 

Demo

+10
source

Source: https://habr.com/ru/post/910521/


All Articles