简体   繁体   English

如何使用JQuery和Ajax写入全局函数?

[英]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. 我想将数据从AJAX处理程序返回到全局变量中。 I have tried making the call non asyc. 我尝试过将通话设置为非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. 我遇到的困难是,当我创建一个全局变量并引用该全局变量时,该值在Ajax请求之外变得不确定。 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 我使呼叫与上一个要解决的问题同步jQuery ajax成功回调函数定义

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 如果希望dataBool是全局变量...则需要是全局变量,而不是局部变量

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. asyc: false是不必要的且拼写错误。 The param is async:false , so that option had no effect, and you don't need it anyways. 该参数是async:false ,因此该选项无效,您也不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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