使用 Ajax 验证 x-editable
Validate x-editable using Ajax
我正在使用 http://vitalets.github.io/x-editable/ and wish to validate an input using Ajax. For testing, I created the following script https://jsfiddle.net/m698gxgj/1/。
我的 Ajax 请求是异步的,所以验证回调 returns 我相信 undefined
,因此它不会导致输入验证失败。
我 "could" 将我的 Ajax 请求更改为同步,但我阅读的所有内容 () 表明这不是一个好主意。
这是如何实现的?
<p>Name</p><a href="javascript:void(0)" id="name"></a>
$('#name').editable({
type: 'text',
title: 'Name',
url: '/echo/json/',
pk: 123,
validate: function (value) {
if (value == 'bob') {
return 'bob is not allowed';
} else {
$.post('/echo/html/', {
html: 'false',
delay: .5
}, function (result) {
if (result == 'false') {
console.log('remote error');
return 'remote error';
}
});
}
}
});
validate
选项仅用于客户端验证,因此 if (value == 'bob')
位没问题,但您不应该触发 ajax post在 else
块中。
您应该让 url
选项执行 ajax post,然后您可以利用 success
和 error
选项正确处理异步回调.
例如:
$('#name').editable({
type: 'text',
title: 'Name',
url: function () {
return $.post('/echo/json/', {
json: 'false',
delay: .5
});
},
pk: 123,
validate: function (value) {
if (value == 'bob') {
return 'bob is not allowed';
}
},
success: function (response) {
if(response === false) {
console.log('remote error from success');
return 'remote error';
}
},
error: function (response) {
console.log('remote error from fail');
return 'remote error';
}
});
jsfiddle:
https://jsfiddle.net/x0bdavn7/
我正在使用 http://vitalets.github.io/x-editable/ and wish to validate an input using Ajax. For testing, I created the following script https://jsfiddle.net/m698gxgj/1/。
我的 Ajax 请求是异步的,所以验证回调 returns 我相信 undefined
,因此它不会导致输入验证失败。
我 "could" 将我的 Ajax 请求更改为同步,但我阅读的所有内容 () 表明这不是一个好主意。
这是如何实现的?
<p>Name</p><a href="javascript:void(0)" id="name"></a>
$('#name').editable({
type: 'text',
title: 'Name',
url: '/echo/json/',
pk: 123,
validate: function (value) {
if (value == 'bob') {
return 'bob is not allowed';
} else {
$.post('/echo/html/', {
html: 'false',
delay: .5
}, function (result) {
if (result == 'false') {
console.log('remote error');
return 'remote error';
}
});
}
}
});
validate
选项仅用于客户端验证,因此 if (value == 'bob')
位没问题,但您不应该触发 ajax post在 else
块中。
您应该让 url
选项执行 ajax post,然后您可以利用 success
和 error
选项正确处理异步回调.
例如:
$('#name').editable({
type: 'text',
title: 'Name',
url: function () {
return $.post('/echo/json/', {
json: 'false',
delay: .5
});
},
pk: 123,
validate: function (value) {
if (value == 'bob') {
return 'bob is not allowed';
}
},
success: function (response) {
if(response === false) {
console.log('remote error from success');
return 'remote error';
}
},
error: function (response) {
console.log('remote error from fail');
return 'remote error';
}
});
jsfiddle: https://jsfiddle.net/x0bdavn7/