如何等待ajax请求? [英] How to await the ajax request?

查看:99
本文介绍了如何等待ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个JS代码,如果数据库中已存在给定的数字,它将取消btn_submit按钮.onclick事件。我使用AJAX查询给定数字的数据库,并确定是否应该将数据发送到将上传问题的.php站点。为了确定这一点,我需要numOfRows变量的值,但因为我在AJAX中设置它将保持为0. validation()函数将在我的AJAX查询完成之前完成,这会导致问题始终表明给定的数字不是存在于DB中(numOfRows将始终保持为0)。
在我的validation()函数的结束行中将numOfRows与0进行比较之前,我如何等待AJAX​​查询完成?如果数字中已存在该数字,我需要将false返回到此行:

I am trying to write a JS code that will cancel the "btn_submit" buttons .onclick event if the given number already exists in the database. I use AJAX to query the DB for the given number and to determine if the should send the data to a .php site which will upload the question. To determine this I need the numOfRows variable's value, but because I set it in AJAX it will stay on 0. The validation() function will finish before my AJAX query finishes and this causes the problem that will always state that the given number does not exist in the DB (numOfRows will always stay on 0). How can I await the AJAX query's finish before I compare the numOfRows to 0 in my validation() function's ending lines? If the number already exists in the DB, I need to return false to this line:


document.getElementById(btn_submit)。onclick =验证;

document.getElementById("btn_submit").onclick = validation;

谢谢!

var textAreaList;
var numOfRows = 0;
var finished = false;

document.getElementById("btn_submit").onclick = validation;

textAreaList = document.getElementsByClassName("text_input");

function validation() {
    loadNumRows();

    try {
        document.getElementById('failure').hidden = true;
    }
     catch(e) {
         console.log(e.message);
     }
    textAreaList = document.getElementsByClassName("text_input");
    var failValidation = false;
    for (var i = 0; i < textAreaList.length; i++) {
        console.log(textAreaList[i]);
        if (textAreaList[i].value == "") {
            textAreaList[i].style.border = "2px solid #ff0000";
            failValidation = true;
        } else {
            textAreaList[i].style.border = "2px solid #286C2B";
        }
    }

    return !(failValidation || numOfRows != 0);
}

function loadNumRows(){
    $.ajax({
        url: 'php/SeeIfNumberExists?number=' + document.getElementById('number_inp').value,
        type: "GET",
        cache: false,
        success: function (html) {
           numOfRows = parseInt(html);               
        }
    });
}


推荐答案

使用 async:false 是一个非常糟糕的主意,并且首先打败了使用AJAX的全部目的--AJAX意味着异步。如果您想在进行AJAX调用时等待脚本的响应,只需使用延迟对象和承诺:

Using async: false is an extremely bad idea, and defeats the whole purpose of using AJAX at the first place — AJAX is meant to be asynchronous. If you want to wait for a response from your script when you make the AJAX call, simply use deferred objects and promises:

var validation = function () {
    var numberCheck = $.ajax({
        url: 'php/SeeIfNumberExists?number=' + $('#number_inp').val(),
        type: "GET"
    });

    // Listen to AJAX completion
    numberCheck.done(function(html) {
        var numOfRows = parseInt(html),
            textAreaList = $('.text_input'),
            finished = false;

        // Rest of your code starts here
        try {
            document.getElementById('failure').hidden = true;
        }
        catch(e) {
            console.log(e.message);
        }

        // ... and the rest
    });

}

// Bind events using jQuery
$('#btn_submit').click(validation);

我在你的代码中看到你使用的是原生JS和jQuery的混合物 - 它有助于你坚持一个:)

I see in your code that you are using a mixture of both native JS and jQuery — it helps if you stick to one :)

这篇关于如何等待ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆