繁体   English   中英

使用Ajax验证x可编辑

[英]Validate x-editable using Ajax

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

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

我“可以”将我的Ajax请求更改为同步,但是我阅读的所有内容( https://stackoverflow.com/a/14220323/1032531 )都表明这不是一个好主意。

如何完成的?

<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')位还可以,但是您不应在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';
    }
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM