Ajax call in second (cross browser)
I have
<a href="url" onclick="var msg = confirm('Confirm?'); submit(msg, event);">Click me</a>
What I want to do is take the confirmation box result (true/false), pass it to the submit button, and then kill the href call if its false.
I have it working in my development environment, but when I load this into a cross browser scenario, the second call isn't working:
function submit(msg, evt) {
if(msg == true) {
$.ajax({
type:"POST",
data:{answer:'Correct'},
url:'https://myurl/p'
});
}
else { evt.preventDefault(); return false; }
}
The URL passed is just the URL and has no data to it (in production). This exact code works perfectly fine in my environment, but in the cross browser scenario it fails. If I remove the confirmation box, everything works perfectly.
I have a feeling it's tied to the preventDefault call on the cancel of the confirmation box. Would that preventDefault disable the next call out with that same link?
First of all, please don't use inline event handlers, you can remove this from the markup and deal with it in your js where it belongs:
HTML:
<a href="url" id="myanchor">Click me</a>
JS:
anchor = $('#myanchor')[0];
anchor.on('click',function(){
var msg = confirm('Confirm?');
submit(msg, event);
});
Secondly, if msg is true the ajax call is immediately interrupted by a page redirect, which doesn't make much sense. I believe you want the redirect to take place once the ajax call has completed, in which case you should use:
function submit(msg, evt) {
if(msg == true) {
$.ajax({
type:"POST",
data:{answer:'Correct'},
url:'https://myurl/p',
complete: function(){window.location="url";}
});
}
evt.preventDefault();
return false;
}
<a href="url" ID="myUrlID">Click me</a>
$(function(){
$("#myUrlID").click(function(event){
event.preventDefault();
var msg = confirm('Confirm?');
if(msg == true) {
$.ajax({
type:"POST",
data:{answer:'Correct'},
url:'https://myurl/p'
});
}
});
});
链接地址: http://www.djcxy.com/p/71704.html
上一篇: 如何从确认对话框插件返回布尔值?
下一篇: 第二个Ajax调用(跨浏览器)