简体   繁体   中英

How do you write to a global function with JQuery and Ajax?

I want to return data from a AJAX handler into a global variable. I have tried making the call non asyc. The difficulty I am having is when I create a global variable and I make reference to that global variable the value becomes undefined outside the Ajax request. I have even tried calling a function using my success callback without any luck. Here is what it looks like at the moment. I made the call sync with a previous question being addressed jQuery ajax success callback function definition

config();
function config()
{
    var dataBool;
    var db_test;
    $.ajax({asyc: false,
            url: 'config.php',
            dataType: "text",
            data:{db_test:1},
            type: "POST",
            success: dataStuff
    });
    function dataStuff(data)
    {
        dataBool = data;
    }

}

If you want dataBool to be a global variable... it needs to be a global variable, not a local variable

var dataBool;
config();
function config()
{
    var db_test;
    $.ajax({url: 'config.php',
            dataType: "text",
            data:{db_test:1},
            type: "POST",
            success: dataStuff
    });
    function dataStuff(data)
    {
        dataBool = data;
    }

}

asyc: false is unnecessary and misspelled. The param is async:false , so that option had no effect, and you don't need it anyways.

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