Ajax从函数获取验证,然后将响应传递给另一个ajax?

时间:2018-01-19 14:23:01

标签: javascript jquery ajax callback promise

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

 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.');
                }

            });
        }
    }

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

From='0'

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

2 个答案:

答案 0 :(得分:1)

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

    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);

            }
        })
        }

和其他代码,即验证True或False:

    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;
    }

答案 1 :(得分:0)

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

基本上,你的方法必须返回一个Promise OBject。有了这些,你可以调用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