I have some jQuery which uses an each loop to go through values entered in a repeated form field on a Symfony 3 CRM. There is a $.post which sends the entered value to a function that checks for duplicates in the database, and if it's a duplicate it adds something to an array, otherwise it adds a blank value to indicate it's not a dupe. Once these have been done, it then checks the final array and adds any errors to the error block to display to the user.

我有一些jQuery,它使用每个循环遍历在Symfony 3 CRM的重复表单字段中输入的值。有一个美元。post将输入的值发送到一个函数,该函数检查数据库中的重复项,如果是重复项,则向数组中添加一些内容,否则将添加一个空值,以表明它不是dupe。一旦完成这些操作,它就会检查最终的数组,并向错误块中添加任何错误以显示给用户。

However, it seems that the array is ALWAYS blank and I belivee it's because it's running the code that displays the errors BEFORE it's actually finished getting the response.

但是,看起来这个数组总是为空的,我相信这是因为它运行的代码在它真正得到响应之前显示错误。

Here is my code:

这是我的代码:

$('#puppy_form').on('submit', function() {
    var bitch_errors = [];
    var dog_errors = [];
    // NOTE: Bitch and dog names need to be checked differently so we know which error is assigned to which input
    $('.check_bitch_name').each( function(i, obj) {
        // need to check each name for validity and duplication.
        var entered_bitch_name = obj.value;
        var pattern = /^[a-zA-Z,.]+\s[a-zA-Z,.]+(\s[a-zA-Z,.]+){0,}$/;
        if(!pattern.test(entered_bitch_name)) {
            bitch_errors[i+1] = "invalid";
        } else {
            // now to check for duplicates
            $.post('/check-puppy-name', { name: entered_bitch_name }
            ).done(function (response) {
                if(response == 'duplicate') {
                    bitch_errors[i+1] = "duplicate";
                } else {
                    bitch_errors[i+1] = "";
                }
            });
        }
    });
    $('.check_dog_name').each( function(i, obj) {
        // need to check each name for validity and duplication.
        var entered_dog_name = obj.value;
        var pattern = /^[a-zA-Z,.]+\s[a-zA-Z,.]+(\s[a-zA-Z,.]+){0,}$/;
        if(!pattern.test(entered_dog_name)) {
            dog_errors[i+1] = "invalid";
        } else {
            // now to check for duplicates
            $.post('/check-puppy-name', { name: entered_dog_name }
            ).done(function (response) {
                if(response == 'duplicate') {
                    dog_errors[i+1] = "duplicate";
                } else {
                    dog_errors[i+1] = "";
                }
            });
        }
    });


    if(count(bitch_errors) == 0 && count(dog_errors) == 0) {
        return true;
    }

    // loop through the errors and assign them to the correct input
    $.each( bitch_errors, function( key, value ) {
        if (value == "invalid") {
            $('input[name="bitch_name['+key+']"]').parent().addClass('has-error');
            $('input[name="bitch_name['+key+']"]').next('.error-message').html('Names must be at least two words, and only contain letters');
            return false;
        } else if(value == "duplicate") {
            $('input[name="bitch_name['+key+']"]').parent().addClass('has-error');
            $('input[name="bitch_name['+key+']"]').next('.error-message').html('Sorry, this name has already been taken');
            return false;
        }
    });
    $.each( dog_errors, function( key, value ) {
        if(value != "") {
            if (value == "invalid") {
                $('input[name="dog_name['+key+']"]').parent().addClass('has-error');
                $('input[name="dog_name['+key+']"]').next('.error-message').html('Names must be at least two words, and only contain letters');
                return false;
            } else if(value == "duplicate") {
                $('input[name="dog_name['+key+']"]').parent().addClass('has-error');
                $('input[name="dog_name['+key+']"]').next('.error-message').html('Sorry, this name has already been taken');
                return false;
            }
        }
    });

    return false;

});

Basically, it first checks that the inputted name is valid, then posts off and checks for dupes. The issue is, even though it does the validity check (and prints errors accordingly) it seems to ignore the dupe check and carry on before it's even called back the first response.

基本上,它首先检查输入的名称是否有效,然后发布和检查dupes。问题是,尽管它进行了有效性检查(并相应地打印错误),但它似乎忽略了dupe检查并在第一个响应被回调之前继续执行。

How can I make sure it's finished it's checking before going on and adding the errors to the form? I've tried other solutions including attempting to implement the $.when functionality in jQuery but I don't really understand how to make it work. Any help appreciated.

如何确保它已经完成,在继续之前进行检查并将错误添加到表单中?我尝试过其他解决方案,包括尝试实现$。当jQuery的功能,但我不知道如何使它起作用。任何帮助表示赞赏。

3 个解决方案

#1


2

First, write a function that returns an asynchronous promise to give you a value for one dog:

首先,编写一个函数,返回一个异步承诺,为一条狗提供一个值:

function checkDog(name) {
    var pattern = /^[a-zA-Z,.]+\s[a-zA-Z,.]+(\s[a-zA-Z,.]+){0,}$/;
    if(!pattern.test(name)) {
        return $.Deferred().resolve("invalid");
    } else {
        return $.post('/check-puppy-name', { name: name } )
         .then(function (response) {
            if (response === 'duplicate') {
                return 'duplicate';
            } else {
                return '';
            }
        });
    }
}

Then you can write one that handles multiple dogs, also returning a promise (which won't itself be resolved until every dog has been checked):

然后你可以写一篇文章来处理多只狗,并返回一个承诺(这个承诺在每只狗都被检查完之后才会得到解决):

function checkDogs(array) {
    return $.when.apply($, array.map(checkDog));
}

Note that there's no DOM-related code yet. You can now write a function that gets the values from a bunch of DOM inputs and returns them in an array:

注意,目前还没有与域相关的代码。现在,您可以编写一个函数,该函数从一堆DOM输入中获取值,并在数组中返回值:

function getInputValues($selector) {
    return $selector.get().map(function(el) {
        return el.value;
    });
}

So now (on submit) you can check your two sets of inputs and then finally when both of these are available, you can examine the results and update the DOM:

所以现在(提交时)你可以检查两组输入,最后当这两组输入都可用时,你可以检查结果并更新DOM:

$('#puppy_form').on('submit', function() {

    var bitch_names = getInputValues($('.check_bitch_name'));
    var dog_names = getInputValues($('.check_dog_name'));

    var bitch_promises = checkDogs(bitch_names);
    var dog_promises = checkDogs(dog_names);

    $.when(bitch_promises, dog_promises).then(function(bitch_errors, dog_errors) {
        // update the DOM based on the passed arrays
        ...
    });
});

更多相关文章

  1. 如何将表列转换为数组?
  2. 点击JSON数据加载Galleria画廊。我需要新鲜的眼睛来看我的错误
  3. 如何修复JSON对象的假数组?
  4. jQuery:离线后发布错误(iOS和Chrome)
  5. 如何从SQL SELECT查询中的c#变量创建jQuery数组
  6. 在线请教调用Jquery错误:TypeError: a is undefined 的错误原因
  7. 在发出xml Ajax请求时获取错误412
  8. 导入地址簿联系人,存储在数组中并保存到数据库
  9. Internet Explorer导致无效的真实性令牌错误

随机推荐

  1. Android设置多个闹钟
  2. 64位win7操作系统 Android(安卓)开发环境
  3. android时区的初始化
  4. Android(安卓)Studio SDK 各版本下载方法
  5. Android客户端对服务端返回的xml文件内容
  6. Android处理9.png文件流程
  7. Android 3.0 r1 API中文文档(106) —— S
  8. Android 项目中集成 Flutter
  9. Android 3.0动画学习笔记
  10. Eclipse+android 开发配置步骤