【问题标题】:Ajax Get Validation from function, then pass the response to another ajax?Ajax 从函数获取验证,然后将响应传递给另一个 ajax?
【发布时间】:2018-06-28 19:39:39
【问题描述】:

我有一个验证页面上的文本框的 ajax 函数, 然后我需要对该值做一些事情(在数据库中搜索并在文本框中显示结果)。 然后,我需要另一个不同功能的验证功能。所以..

        function validarRut(textBox) {
        var resultado;
        $.ajax({
            type: "POST",
            url: "AgendarInduccion.aspx/validarRut",
            data: "{rut:" + JSON.stringify(textBox) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function(response){
                alert("valido");
            },
            failure: function (response) {
                alert("ERROR");
            }
        });

    }

这是验证功能(有效!): 以及在数据库中搜索的功能:

 function buscarEmpresa(textBox) {
        var res;
        res = validarRut(textBox.value); // I need the result, to works with this function.!


        alert("VALOR" + res);
        if (res) {
            var resultado;
            $.ajax({
                type: "POST",
                url: "/AgendarInduccion.aspx/buscarEmpresa",
                data: "{RutEmpresa:" + JSON.stringify(textBox.value) + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (response) {
                    resultado = response.d;
                    var nombre = resultado[0];
                    var razonSocial = resultado[1];
                    var direccion = resultado[2];
                    if (nombre == "nulo") {
                        alert("El Rut de la Empresa No se ha Encontrado en Nuestra Base de Datos, favor de ingresar!");
                        // crear empresa!
                        // la institucion no existe; se debe crear una!
                        //btGuardar.Visible = true;
                        //btCancelar.Visible = true;

                        //txtRutEmpresa.Enabled = false;
                        //txtNombreEmpresa.Enabled = true;
                        //txtRazonSocial.Enabled = true;
                        //txtDireccion.Enabled = true;
                        document.getElementById('<%= txtRutEmpresa.ClientID %>').disabled = true;
                        document.getElementById('<%= txtNombreEmpresa.ClientID %>').disabled = false;
                        document.getElementById('<%= txtRazonSocial.ClientID %>').disabled = false;
                        document.getElementById('<%= txtDireccion.ClientID %>').disabled = false;

                        $('#<%= txtRazonSocial.ClientID%>').val(razonSocial); //razon social desde SII

                        document.getElementById('<%=btGuardar.ClientID %>').style.display = 'inline';
                        document.getElementById('<%=btCancelar.ClientID %>').style.display = 'inline';
                        document.getElementById('<%=btActualizar.ClientID %>').style.display = 'none';




                    } else {
                        $('#<%= txtNombreEmpresa.ClientID%>').val(nombre);
                        $('#<%= txtRazonSocial.ClientID%>').val(razonSocial);
                        $('#<%= txtDireccion.ClientID%>').val(direccion);
                    }
                },
                failure: function () {
                    alert('No Realizado.');
                }

            });
        }
    }

我还有第三个使用“function validarRut(textBox)”的函数;所以我不想把搜索功能放在成功中,因为我需要重新使用该功能。有什么帮助吗? PD: async: false 不适合我。

【问题讨论】:

  • success: function(response){ buscarEmpresa(textBox) },
  • 如果 async:false 不是一个选项,你为什么要使用它?
  • 因为我在测试,但是是一个不好的解决方案;抱歉未注释
  • @mplungjan 如果我在 validarRut(textBox); 中使用它我不能重用与 buscarEmpresa(textBox) 不同的另一个函数
  • function validarRut(textBox,search) { var callSearch = search;success: function(response){ if (search) buscarEmpresa(textBox) }, - 现在您可以通过 validarRut(textBox,true) 搜索或通过 validarRut(textBox) 不搜索

标签: javascript jquery ajax callback promise


【解决方案1】:

如果我正确地解决了你的问题,Promises 会解决你的问题。

基本上,您的方法必须返回一个 Promise 对象。有了这些,你可以调用 then(),它会在 Promise 被解决(成功)或被拒绝(错误)时立即执行

所以基本上你的代码必须像这样工作:

 function validarRut(value) {
  return new Promise(resolve, reject){
    $.ajax({
      type: "get",
      url: "/",
      success: function (response) {
        resolve(response); // when this is called, every then() function gets executed
      },
      failure: function (response) {
        reject(response); // when this is called, every catch() function gets executed
      }
  });
  }

}

function buscarEmpresa(textBox) {
  var res;
  validarRut(textBox.value).then(function (res) {
    // res is whatever you passed the resolve function
    if (res) {
      textbox.text(res.toString());
      // do whatever you want with the result
    }
  })
  .catch(error){
    // error is whatever you passed the reject function
  }
}

$(document).ready(() => {
  buscarEmpresa($('#result'));
})

观看实际操作: https://jsfiddle.net/yygggbsa/

Promise 是这种异步调用的方式。但请记住,它们在 IE11 中不可用:

https://caniuse.com/#feat=promises

因此,如果您需要支持 IE11 等旧版浏览器,则需要添加一个外部库。

进一步阅读:

在 IE11 中使用 Promise:How to make promises work in IE11

在 MDN 上的承诺:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

【讨论】:

  • 非常有建设性的批评。不是。砰。 (如果你不知道它的意思,谷歌它。)
  • 只是一个好建议。你很有可能被无情地投票否决,无法恢复
  • stackoverflow 社区真的那么有毒吗?我只是想让 OP 知道我正在制作小提琴……坦率地说,如果我被否决,我真的不在乎。正如你所看到的,我并不那么渴望声誉。我想提供帮助,我知道我的解决方案是正确的,如果其他人不同意,请随意。
  • 只是不要发布空答案。谁知道你什么时候会回来或放弃。请阅读此内容及其副本:meta.stackoverflow.com/questions/269993/…
  • 哈。谢谢你的建议。我现在明白了,但这对我来说并不成立,因为我总是在解决我的承诺(双关语强烈)。
【解决方案2】:

这是我的解决方案!非常感谢

    function buscarEmpresaPromise(textBox) {
        var res;
        validarRutPromise(textBox.value).then(function (res) {
            if (res.d) {
                alert(">hola");
                alert("Rut validado CORRECTAMENTE");
            } else {
                alert("Rut invalido, vuelva a ingresar porfavor: " + textBox.value);

            }
        })
        }

以及验证真假的其他代码:

    function validarRutPromise(textBox) {
        var promise = new Promise(function (resolve, reject) {
            $.ajax({
                type: "Post",
                url: "AgendarInduccion.aspx/validarRut",
                data: "{rut:" + JSON.stringify(textBox) + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                complete: function (response) {
                    resolve(response);
                },
                fail: function (response) {
                    reject(response);
                }
            });
        })
        return promise;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2018-10-02
    • 2020-09-24
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多