我想做以下小脚本/事情。 有一个注册表单,我希望jquery检查键入的数据(例如登录名和/或电子邮件地址)是否与cakephp验证规则匹配,并在可爱的消息框中将该信息返回给用户。 所以我构建了以下(简化):
$("input#UserDisplayName").keyup(function() {
var value = $(this).val();
var status = validateAgainstCakeModel('display_name', value);
var box = $("#DisplayNameMessage");
if ( status == "true" ) {
// show box with a message and so on ...
var message = "This Name is available.";
updateMessageBox( 0, box, message );
} else {
var message = " asdhasjkdhasd";
updateMessageBox( 0, box, message );
}
}
验证方法:
function validateAndUpdateMessageBox( field , value ) {
// prepare & send ajax request
$.ajax({
url: "register",
type: "POST",
timeout: 5000,
data: { action: "validate", field: field, value: value },
success: function( result ) {
response = result;
}
});
return response;
}
所以问题是整个事情的异步性。在返回响应时,将不会有任何数据,因此该函数将返回“undefined”。
是的,我知道“async:false”选项,但这会将浏览器锁定一秒钟(或更多)。 是否还有其他解决方案可以像这样编码并且不锁定浏览器?
感谢您的回答。
答案 0 :(得分:2)
提供稍后作为回调执行的代码
$("input#UserDisplayName").keyup(function() {
var value = $(this).val();
validateAgainstCakeModel('display_name', value, function(status) {
var box = $("#DisplayNameMessage");
if ( status == "true" ) {
// show box with a message and so on ...
var message = "This Name is available.";
updateMessageBox( 0, box, message );
} else {
var message = " asdhasjkdhasd";
updateMessageBox( 0, box, message );
}
});
}
function validateAndUpdateMessageBox( field , value, callback ) {
// prepare & send ajax request
$.ajax({
url: "register",
type: "POST",
timeout: 5000,
data: { action: "validate", field: field, value: value },
success: function( result ) {
callback.call(this, result );
}
});
}
答案 1 :(得分:0)
callback
,这可能会更有用
$("input#UserDisplayName").keyup(function() {
var value = $(this).val();
var box = $("#DisplayNameMessage");
$.ajax({
url: "register",
type: "POST",
timeout: 5000,
data: { action: "validate", field: 'display_name', value: value },
success: function( result ) {
if ( status == true ) {
// show box with a message and so on ...
var message = "This Name is available.";
updateMessageBox( 0, box, message );
} else {
var message = " asdhasjkdhasd";
updateMessageBox( 0, box, message );
}
}
});
}