jquery工具Overlay:打开基于ajax响应的覆盖
我正在尝试通过单击按钮打开叠加层。该按钮与一个 ajax 调用关联,如果返回错误,则应打开一个覆盖层,但成功后,该覆盖层不会打开。
发生的情况是,无论 ajax 响应是否成功/错误,覆盖层都会打开。它在单击按钮时打开,而不是在 ajax 响应时打开。我在这里缺少什么???
这就是我正在尝试的...
//Overlay setup
$('#PostQuestion').overlay({
target: "#template"
});
//Ajax call setup
$('#PostQuestion').click(function() {
$.ajax({
url: '/ask_away',
dataType: "json",
data: {question: 'something'},
type: 'POST',
cache: false,
success: function(response) {
alert("It was a success");
},
error: function(request, error) {
$('#PostQuestion').data('overlay').load();
}
});
});
<!-- HTML Here -->
<div id="template">You got an error</div>
<div id="PostQuestion">Ask Question</div>
I am trying to open an overlay on a button click. The button has associated with it an ajax call, which if returns an error should open an overlay, but on success the overlay does not open.
What happens is that the overlay opens regardless of success/error in ajax response. It opens on button click, not on ajax response. What am I missing here???
Here is what I am trying...
//Overlay setup
$('#PostQuestion').overlay({
target: "#template"
});
//Ajax call setup
$('#PostQuestion').click(function() {
$.ajax({
url: '/ask_away',
dataType: "json",
data: {question: 'something'},
type: 'POST',
cache: false,
success: function(response) {
alert("It was a success");
},
error: function(request, error) {
$('#PostQuestion').data('overlay').load();
}
});
});
<!-- HTML Here -->
<div id="template">You got an error</div>
<div id="PostQuestion">Ask Question</div>
无论 ajax 调用是否成功/错误,覆盖层都会显示的原因是:
基本上定义了 #PostQuestion div 的单击处理程序以打开覆盖层。因此,一旦您单击 PostQuestion div,您不仅会发送 ajax,还会显示叠加层(正如我所说的上面代码片段的结果)。
要使其按预期工作,请检查下面的代码。还有一个简短的旁注 - 即使 ajax 调用返回 200 OK,但不是正确的 json 数据,错误处理程序也会被使用,所以在开发时请记住这一点。
The reason the overlay is showing regardles of success/error of ajax call is because this:
basically defines click handler for #PostQuestion div to open an overlay. So once you click PostQuestion div you not only sending the ajax but also showing the overlay (which is as I said result of the code snippet above).
To make it work as desired check the code below. Just one more quick side-note - even if the ajax call return 200 OK, but not a proper json data the error handler will be used, so keep that in mind while developing.