我正在开发一个从通过AJAX网络获取数据的部件,我想提供一个错误信息,如果该部件无法连接到服务器。我做与jQuery的Ajax对象,它提供了一个错误回调函数的要求,但在没有互联网连接,只有在提出要求但没有其他原因,它不叫。
现在如何检查计算机是否连接到互联网?
解决方案更新:由于您要创建一个Dashboard小工具,我跑了多次试验
我发现, $。阿贾克斯
调用实际上触发了一个错误,当没有互联网连接。于是我就约了巨大的成功手动创建XMLHTT prequest对象。如果你需要JSON解析,我建议也包括 json2.js 解析器。
的事情我没有做这项工作:的
在控件属性在短跑code,我点击允许网络访问(如果你使用的不是短跑code,检查的文档进行适当的plist设置扭转这一上) 我用下面的code:VAR XHR =新XMLHtt prequest(); xhr.addEventListener('readystatechange',state_change,真正的); xhr.open(GET,URL,真正的); xhr.send(空); 功能state_change(){ 如果(xhr.readyState == 4){ 如果(xhr.status == 200){ 的console.log('工作'); //只有当运行在短跑code工作 //使用xhr.responseText或JSON.parse(xhr.responseText) }否则,如果(xhr.status == 0){ 的console.log('没有互联网'); //只有当运行在短跑code工作 } 其他 { //其他错误 } } }
/结束更新
我编辑我的回答your原来的问题因为你在评论中问它。评论后,我看到你贴了这个问题。
总之,添加暂停
参数给你的 $。阿贾克斯
呼叫并将其设置为较小的数字(像5000毫秒)。您的误差函数将请求超时后调用。
i'm developing a widget that is fetching data from the internet via ajax and i want to provide a error message, if the widget cannot connect to the server. i'm doing the request with jquery's ajax object which provides a error callback function, but it's not called when there is no internet connection, only if the request is made but fails for other reasons.
now how can i check if the computer is connected to the internet?
解决方案UPDATE: Since you are creating a Dashboard widget, I ran a number of tests.
I found that the $.ajax
call actually triggered an error when there was no internet connection. So I went about creating a XMLHTTPRequest object manually with great success. If you need JSON parsing, I suggest also including the json2.js parser.
Things I did to make this work:
In Widget Attributes in Dashcode I clicked "Allow Network Access" (If you aren't using Dashcode, check the docs for the proper plist setting to turn this on) I used the following code:
var xhr = new XMLHttpRequest(); xhr.addEventListener('readystatechange', state_change, true); xhr.open("GET", url, true); xhr.send(null); function state_change(){ if(xhr.readyState == 4){ if(xhr.status == 200){ console.log('worked'); // Only works if running in Dashcode // use xhr.responseText or JSON.parse(xhr.responseText) } else if(xhr.status == 0) { console.log('no internet'); // Only works if running in Dashcode } else { // Some other error } } }
/End Update
I answered this by editing my answer to your original question since you asked it in the comments. After commenting I saw you posted this question.
To summarize, add the timeout
parameter to your $.ajax
call and set it to a low number (like 5000 milliseconds). Your error function will be called after the request times out.