简体   繁体   中英

jquery exit function in ajax call

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

For example, in the below function, hi , if the GET results in 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 go about accomplishing this?

I think the solution can 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 an ajax function synchronous, then the browser will be blocked for the duration of ajax call. Which means that the application will remain non-responsive during the duration of the call.

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'
    ...
}

Creating a global flag variable I think would work the 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'
...
}

One thing you can do is have a flag variable. Assign it to true or false, depending on if 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'
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM