【问题标题】:Form validation: getting asynchronous return value表单验证:获取异步返回值
【发布时间】:2016-04-04 12:58:19
【问题描述】:

我正在学习 ajax。我需要使用 ajax 验证表单以检查用户选择的伪是否存在于 json 文件(users.json)中。我需要获取 var checkPseudo 的值。实际上,这个 var 始终是“未定义的”。

我认为这是异步开发的经典问题。

注意:我可能不会使用 Jquery 库。

这是我的代码

<!-- This is my form -->

<form method="post" id="frmInscription" action="adduser.php" onsubmit="return formValidation(this)">
    Pseudo :<input name="pseudo" type="text" /><br />
    <input type="submit" name="send" value="Submit" />
</form>


<!-- javascript functions to validate the form -->

function makeRequestCheckPseudo(callback){
    if(xhr = createXhr()){ // returns an xhr object
        xhr.open("GET", "users.json", true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                //I use a callback function to get the ajax responseText in the function formValidation(frm)
                callback.apply(xhr);
                return callback(); //I'm not sure if I need to return the callback function
            }                
        }
        xhr.send(null);
    };
}

function formValidation(form){
    var pseudo = form.elements["name"].value;                
    var checkPseudo = makeRequestCheckPseudo(function(){
        var jsonPseudos = JSON.parse(this.responseText); // here I get the datas from users.json by ajax response
        if(!jsonPseudos[pseudo]){ //if pseudo is present in the json object properties
            alert("pseudo is not present in users.json !");
            return true; // I want to send my form
        } else {
            alert("pseudo is present users.json !");
            return false; // I don't want to send my form          
        }
    });
    return checkPseudo; // should be "true" or "false" but I get "undefined" 
    //if checkPseudo is false the form will not be send
    //if checkPseudo is true the form will be send
}

【问题讨论】:

  • 您在获取元素值时犯了错误,这应该是var pseudo = form.elements["pseudo"].value;;

标签: javascript ajax asynchronous


【解决方案1】:

因为这就是异步程序的工作方式。

你可以做的是默认阻止表单提交,如果验证成功则手动调用表单的提交方法

function makeRequestCheckPseudo(pseudo, callback) {
  if (xhr = createXhr()) { // returns an xhr object
    xhr.open("GET", "users.json", true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        //I use a callback function to get the ajax responseText in the function formValidation(frm)
        callback.apply(xhr);
        callback(); //I'm not sure if I need to return the callback function
      }
    }
    xhr.send(null);
  };
}

function formValidation(form) {
  var pseudo = form.elements["name"].value;
  var checkPseudo = makeRequestCheckPseudo(function() {
    var jsonPseudos = JSON.parse(this.responseText); // here I get the datas from users.json by ajax response
    if (!jsonPseudos[pseudo]) { //if pseudo is present in the json object properties
      alert("pseudo is not present in users.json !");
      form.submit(); //if the validation is successfull then manually trigger the form submit
    } else {
      alert("pseudo is present users.json !");
    }
  });
  return false; //prevent the default action
}

【讨论】:

  • 您的解决方案有效!非常感谢先生!我可以再问你一个问题吗?如果我需要在伪验证之后进行第二次 ajax 验证怎么办?示例:在使用 ajax 检查了伪之后,我想检查电子邮件是否在 email.json 中。我的代码中最好的时刻在哪里进行第二次 ajax 验证?在第一个 ajax 验证里面?
  • form.submit(); 应替换为第二个 ajax 请求,然后在该成功处理程序中您需要执行 form.submit();
  • 好的,我明白了。非常感谢。然后不可能像我希望的那样返回一个值,因为这就是 ajax 的工作方式。先生,我现在不能投票给你,因为我没有足够的声誉,但我保证会回来,因为你让我很生气。请尊重我
  • 我现在不能接受,因为 stackoverflow 的系统告诉我需要更多的“声誉”分数才能投票。 . .所以我所能做的就是向你保证,当我的声誉足够高时,我会回来接受你的回答......我不会忘记你@Arun P Johny。
  • @zm455 没有投票,有一个accept 勾号
【解决方案2】:

您忘记将pseudo 作为第一个参数传递。可能会解决问题。

function formValidation(form){
    var pseudo = form.elements["name"].value;                
    var checkPseudo = makeRequestCheckPseudo(pseudo, function(){
        // rest of the code
    })
}

如果是这一行:

return callback();//I'm not sure if I need to return the callback function

我猜你需要返回 callback() 函数。否则返回值不会在该行设置为checkPseudo

var checkPseudo = makeRequestCheckPseudo(pseudo, function(){
    // rest of the code
}

【讨论】:

  • @Rot 谢谢你的建议。事实上,我需要在这里编辑我的代码,因为我通过传递这个“伪”参数来尝试一些测试。我的意思是在我的生产代码中我不使用这个“伪”参数但是非常感谢!
【解决方案3】:

试试这个;)

function formValidation(form){
  var pseudo = form.elements["pseudo"].value;                
  if(xhr = createXhr()){ // returns an xhr object
    xhr.open("GET", "users.json", true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState == 4 && xhr.status == 200){
        var jsonPseudos = JSON.parse(this.responseText); // here I get the datas from users.json by ajax response
        if(!jsonPseudos[pseudo]){ //if pseudo is present in the json object properties
          alert("pseudo is not present in users.json !");
          return true; // I want to send my form
        } else {
          alert("pseudo is present users.json !");
          return false; // I don't want to send my form          
        }            
    }
    xhr.send(null);
  }
}

尝试一个函数,但您在这里以错误的方式引用了一个字段:var pseudo = form.elements["name"].value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-25
    • 2016-07-26
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 2018-04-09
    相关资源
    最近更新 更多