How to await the ajax request?

后端 未结 3 1099
终归单人心
终归单人心 2020-12-15 17:45

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

相关标签:
3条回答
  • 2020-12-15 18:03

    (I acknowledge this is not the best way to go about things, but this is the quickest way to get your code working as is. Really though, you should rethink how you are pulling the numOfRows value so that it will work with truly asynchronous Ajax. All that being said...):

    Start by setting async : false in the $.ajax call. The A in Ajax stands for asynchronous. That means, execution continues rather than waiting for it to return. You want to turn that off (i.e. make it synchronous). Actually, that should be the whole solution given the code you have there.

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

    One caveat from the docs for $.ajax:

    Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

    0 讨论(0)
  • 2020-12-15 18:08

    use of async/await with a transpilers like Babel to get it working in older browsers. You’ll also have to install this Babel preset and polyfill from npm: npm i -D babel-preset-env babel-polyfill.

    function getData(ajaxurl) { 
      return $.ajax({
        url: ajaxurl,
        type: 'GET',
      });
    };
    
    async function test() {
      try {
        const res = await getData('https://api.icndb.com/jokes/random')
        console.log(res)
      } catch(err) {
        console.log(err);
      }
    }
    
    test();
    

    or the .then callback is just another way to write the same logic.

    getData(ajaxurl).then(function(res) {
        console.log(res)
    }
    
    0 讨论(0)
  • 2020-12-15 18:24

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

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

    0 讨论(0)
提交回复
热议问题