JQuery: Return $.get() callback to outer scope

后端 未结 4 865
生来不讨喜
生来不讨喜 2020-12-22 07:00

I\'m working on this validation script for my latest project, and one of the requirements is that it checks if the value that the user enters is in the database, and if it i

4条回答
  •  半阙折子戏
    2020-12-22 07:33

    The issue is that get is simply a shortcut for doing an AJAX get request. AJAX is asynchronous, so the request is returning after you've checked the variable. You have a few options here. Normally I don't encourage blocking on an ajax call (kind of defeats the purpose), but if this is happening on submit, then it may make sense.

    You can change get to ajax and set async: false. This will wait for the request to finish before moving on.

    If you have multiple such calls that you need to wait for, you should have a look at http://api.jquery.com/jQuery.when/ , this will allow the requests to run in parallel, but still wait for all to complete before moving on.

提交回复
热议问题