Jquery exit function in ajax call

Is there any way to exit the function, depending on the result of the GET request.

For example, in the hi function below, if GET leads to data , where data === '1' , I want to exit the function.

 function hi () { $.ajax({ url: "/shop/haveItem", type: "GET", success: function (data) { if (data == '1') { // exit hi() function } } }); // some executable code when data is not '1' } 

How can i do this?

+4
source share
4 answers

I think the solution may be something like this

 function hi () { $.ajax({ url: "/shop/haveItem", type: "GET", success: function (data) { if (data == '1') { ifData1(); } else { ifDataNot1() } } }); } function ifData1 () { /* etc */ } function ifDataNot1 () { /* etc */ } 

If you have an ajax function, you should always work with callback functions. If you make the ajax function synchronous, the browser will be blocked for the duration of the ajax call. This means that the application will remain immune for the duration of the call.

+9
source

You should be able to return false to simulate "exit".

 function hi() { $.ajax({ url: "/shop/haveItem", type: "GET", async:false, success: function(data){ if(data == '1') return false } }); //some executable code when data is not '1' ... } 
+1
source

One thing you can do is to have a flag variable. Assign it to true or false, depending on whether you want to exit or not.

 function hi() { var flag=false; $.ajax({ url: "/shop/haveItem", type: "GET", async:false, success: function(data){ if(data == '1') flag=true; } }); if ( flag ) return; //some executable code when data is not '1' ... } 
0
source

Creating a global flag variable, I think, will work best. Tested and working!

 window.flag = []; function hi() { $.ajax({ url: "/shop/haveItem", type: "GET", async:false, success: function(data){ if(data == '1') flag = true; } }); if (flag) { return false; } //some executable code when data is not '1' ... } 
0
source

Source: https://habr.com/ru/post/1333136/


All Articles