在ajax完成的函数调用中触发失败

时间:2019-03-20 20:06:50

标签: jquery ajax

我想对ajax调用中收到的数据进行一些检查,如果传递成功,则继续执行发布请求。

提交表单后,我向GET发出了一个api/customers/all请求,其中包含一个用户名对象。我想检查formData中包含的数据在该对象中不存在。这是我正在尝试的:

$( document ).ready(function() {

    // SUBMIT FORM
    $("#userForm").submit(function(event) {
        event.preventDefault();
        if(checkName()){
        //Post the data somewhere
            ajaxPost();
        } 
    });


    function checkName(){

        // PREPARE FORM DATA
        var formData = {
            firstname : $("#firstname").val()
        }

        var addName = true;

        // GET POST
        $.ajax({
            type : "GET",
            contentType : "application/json",
            url : window.location + "api/customers/all",
            dataType : 'json'})
            .done(function(names) {

                var allNames = [];

                $.each(names, function(i, name){
                    allNames.push(name.firstname);
                });

                console.log("Here is the entered name: " + formData.firstname);

                if(!allNames.includes(formData.firstname)){
                    if(confirm("Are you sure you want to add " + formData.firstname + " as a new name?")){
                        console.log(formData.firstname + " is going to be added to the database");
                        // PASS
                    } else{
                        console.log(formData.firstname + " will NOT to added to the database");
                        // FAIL
                    }
                // PASS
                }
            })
            .fail(function(e) {
                alert("Error!")
                console.log("ERROR: ", e);
            });
    }

})

仅当我的ajaxPost()函数调用通过时,我才想继续进行.done。这可能吗?

1 个答案:

答案 0 :(得分:0)

您好,古谷是一个例子:

html:

  <body>
    <label for="txtName">Name: </label>
    <input type="text" name="txtName" id="txtName" >
    <br>
    <input type="button" name="btnTestMe" id="btnTestMe" value="Test Me !!">
  </body>

json:

{
    "names": [{
            "name": "Tom Cruise",
            "age": 56
        },
        {
            "name": "Robert Downey Jr.",
            "age": 53
        },
        {
            "name": "Stan Chacon",
            "age": 1000
        }
    ]
}

js:

//this function will do a recursive loop to find the value on your json array
  function findInObject(o, f) {
  return Object.keys(o).some(function (a) {
      if (Array.isArray(o[a]) || typeof o[a] === 'object' && o[a] !== null) {
          return findInObject(o[a], f);
      }
      return o[a] === f;
  });
}
//function that return an ajax call this will helps us to manage the done
function ajaxRequest (name){
return $.ajax({
  url: 'names.json',
  type: 'GET',
  dataType: 'JSON'
})
}
//click event to trigger the ajax function
$('#btnTestMe').on('click', function(event) {
  var name = $('#txtName').val();
  ajaxRequest(name)
  .done(function(response) {
    var status = findInObject(response,name);
    if (status) {
      console.log("name is already on db");
    }else {
      console.log("name is avaliable on db =)");
    }
  })
  .fail(function(response) {
    console.log("error");
  })
  .always(function(response) {
    console.log("do another stuff here like load a dialog :D");
  });

希望有帮助

相关问题