[英]localStorage issue when doing ajax
I have some simple code that will run to check Internet connectivity and I'm using localStorage
to hold the variable value and yet when I run it the value of that variable isn't effected. 我有一些简单的代码将运行以检查Internet连接,我使用
localStorage
来保存变量值,但是当我运行它时,该变量的值不受影响。 So, what can I do to fix it. 那么,我该怎么做才能解决它。 Please help.
请帮忙。 If the state is changed to
true
the submit will happen else otherwise it will be prevented. 如果状态更改为
true
则提交将发生,否则将被阻止。
localStorage.setItem("state","");
function checkConnection(){
$.ajax({
url:"assets/ping.js",
success:function(res){
localStorage.setItem("state","true");
},
onerror:function(){
localStorage.setItem("state","false");
}
});
}
$("form").submit(function(e){
checkConnection();
if(localStorage.getItem("state") == "false"){
return false;
} else if(localStorage.getItem("state") == "true") {
return true;
}
});
This is a sychronization isssue. 这是一个同步问题。 Your API call to check the connection does not complete before the form is submitted.
在提交表单之前,您的API调用检查连接未完成。 You want the AJAX call to block until it gets a response.
您希望AJAX调用阻止,直到它得到响应。 (actually I guess it should be called SJAX for synchronous).
(实际上我猜它应该被称为SJAX for synchronous)。
You have to add async
is false
to the settings parameter. 您必须将
async
is false
添加到settings参数。 Read: http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings 阅读: http : //api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
Here is how you do that with jQuery: 以下是使用jQuery执行此操作的方法:
$.ajax({
url:"assets/ping.js",
async: false
success:function(res){
localStorage.setItem("state", "true");
},
error: function(){
localStorage.setItem("state","false");
}
});
Also note that the error handler should be under error
not onerror
. 还要注意的是,错误处理程序应该是在
error
不onerror
。
Finally, if all you are trying to do is detect if the Internet connection was lost you can do that on most browsers by checking the value of window.navigator.onLine. 最后,如果您要做的就是检测Internet连接是否丢失,您可以通过检查window.navigator.onLine的值在大多数浏览器上执行此操作。 See: http://www.whatwg.org/specs/web-apps/current-work/#browser-state
请参阅: http : //www.whatwg.org/specs/web-apps/current-work/#browser-state
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.