使用Ajax验证x-editable

use*_*531 1 javascript ajax jquery x-editable

我正在使用http://vitalets.github.io/x-editable/并希望使用Ajax验证输入.为了测试,我创建了以下脚本https://jsfiddle.net/m698gxgj/1/.

我的Ajax请求是异步的,所以我相信validate回调返回undefined,因此它不会导致输入验证失败.

我"可以"将我的Ajax请求更改为同步,但我读到的所有内容(/sf/answers/995422641/)表明这不是一个好主意.

这是如何完成的?

<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';
                }
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

Sta*_*984 6

validate选项仅用于客户端验证,因此该if (value == 'bob')位正常,但您不应在else块中触发ajax帖子.

您应该url选择执行ajax发布,然后您可以利用successerror选项来正确处理异步回调.

例如:

$('#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';
    }
});
Run Code Online (Sandbox Code Playgroud)

jsfiddle:https://jsfiddle.net/x0bdavn7/