问题描述
这是我的代码:
<script type="text/javascript">
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username() {
$("#check_username").html('<img src="images/site/ajax-loader.gif" />username avilable??').delay(5000);
var usernametotest = $('#username').val();
$.post("backend/username_available.php", { username: usernametotest})
.done(function(data) {
$("#check_username").replaceWith(data);
});
}
</script>
我使用此代码通过AJACX检查表单中用户名的可用性.它工作完美,但只有一次.当用户名被占用并且我更改了用户名时,在第一个用户名之后没有进行AJAX检查吗?文本用户名已经存在"(在变量数据中)不会被用户名确定"代替.
I use this code for checking with AJACX the availability of a username in my form.It works perfect but just once. When an username is occupied and I change the username, no AJAX checks are done after the first one? The text "username already exists" (in the variable data), is not replaced by "username ok".
此JavaScript添加在</html>
标记之前.
This JavaScript is added just before the </html>
tag.
推荐答案
您的代码看起来不错-请参见 jsfiddle 并在usernametotest
值上发出警报,以提高可见度
Your code looks fine - see this jsfiddle with an alert on the usernametotest
value for more visibility
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username(){
$("#check_username").html('username avilable??').delay(5000);
var usernametotest = $('#username').val();
alert('posting username ' + usernametotest);
$.post("backend/username_available.php", { username: usernametotest} )
.done(function(data) {
$("#check_username").replaceWith( data );
});
}
每次都使用正确的有效负载发出发布请求,因此在那里没有问题(请检查浏览器开发者工具,例如Chrome中的网络"标签/XHR)
The post requests are being made every time with the correct payload, so no problems there (check browser developer tools e.g. Network tab / XHR in Chrome)
从backend/username_available.php
返回的响应一定是一个问题吗?检查第一个请求与其他请求的响应,然后发现它们之间的差异,从而使问题可能会突然出现.
Must be an issue with the response coming back from backend/username_available.php
? Check the response of the first request vs the rest, and the difference and hence the problem will probably jump out at you.
这篇关于AJAX通话仅工作一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!