我编写了一个AJAX脚本,该脚本保存表单数据,然后在一次点击事件中显示该数据的预览页面。这是脚本:
$('#ajax-preview').click(function(e) {
var formData = $('#advertiser-edit-form').serializeArray();
$.ajax({
type: 'post' ,
url: "ajax-preview.php",
data: formData,
success: function(data, status, jqXHR) {
previewURL = data;
$('#ajax-preview').attr('href', previewURL);
}
});
});
问题是,有时PHP脚本无法在用户进入预览页面之前完成其保存例程。在这种情况下,用户在进入预览页面时会看到未更新的数据。然后,他必须重新加载页面才能看到更改。
我如何设计脚本,使用户只有在AJAX更新数据后才能进入previewURL
?
问题是,click
处理程序中的代码只启动ajax调用,它不会等待它完成,因此在ajax调用仍在运行时,单击的默认行为(遵循链接)会立即发生。除非您想使ajax调用同步,否则无法使点击事件等待,这会导致用户体验不佳。
相反,我建议用户按下一个按钮来生成预览,这将进行ajax调用,然后让ajax结果显示(取消隐藏)一个链接,用户可以单击该链接来查看预览。
粗略示例:
$("#btn-create-preview").click(function() {
var pending = $("#preview-pending"),
msg = $("#preview-message"),
btn = this;
btn.disabled = true;
msg.hide();
pending.fadeIn("fast");
// Simulate ajax via setTimeout
setTimeout(function() {
// This is the ajax completion function
pending.hide();
msg.find("a").attr(
"href",
"http://example.com?x=" + Math.floor(Math.random() * 10000)
);
msg.fadeIn("fast");
btn.disabled = false;
}, 1000);
});
<input type="button" id="btn-create-preview" value="Create Preview">
<em id="preview-pending" style="display: none">
Building your preview...
</em>
<span id="preview-message" style="display: none">
Your preview is ready;
<a href="">click here</a>
to view it.
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>