【发布时间】:2019-03-07 00:16:03
【问题描述】:
AJAX 新手,我构建了一个包含 AJAX 的表单,它将数据发送到另一个页面。我不确定我是否必须为多个 ajax 请求包含一个插件,或者这是否是自动完成的。到目前为止的问题是 $("#userForm")[0].reset();将等到完全成功后再清除输入字段。我希望它可以立即发送并清除,允许用户快速输入请求并建立一个队列以完成请求。
下面是我的表单/ajax
<html>
<head>
<title>fastPage</title>
</head>
<body>
<form id='userForm'>
<div><input type='text' name='name' /></div>
<div><input type='submit' value='Submit' /></div>
</form>
<div id='response'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
<script>
$(document).ready(function(){
$('#userForm').submit(function(){
// show that something is loading
//$('#response').html("<b>Loading response...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'slowPage.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
//$('#response').html(data);
$("#userForm")[0].reset();
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
</script>
</body>
</html>
slowPage.php 只是为了测试 ajax 调用。
<!DOCTYPE html>
<html>
<head>
<title>slowPage</title>
</head>
<?php
session_start();
echo "
<form action='slowPage.php' method='POST'>
<input type='text' name='name'>
<button type='submit'>Search</button>
</form>";
sleep(10);
if($_POST){
echo $_POST['name'];
}
?>
谁能指出我正确的方向来完成这个?
【问题讨论】:
-
为什么不在 ajax 处理时禁用表单提交?还是您希望他们能够多次提交?
-
我们希望他们尽可能快地提交多次,slowPage 只是复制一个服务器页面,这可能会很慢,以测试这个想法并为请求建立一个队列。跨度>
-
这个答案可能会有所帮助:Queue ajax requests using jQuery.queue().
-
@Yodavish “队列”到底是什么意思?它会等待一个 AJAX 请求完成,然后再将下一个请求发送到服务器?
-
@mhodges 它会等待一个 AJAX 请求完成,然后再将下一个请求发送到服务器?是的。但是,由于服务器页面可能需要 30 秒来处理,我们希望能够“排队”这些 ajax 请求并允许用户在需要时输入更多内容。