jQuery get请求返回未定义的值

时间:2018-07-26 21:26:43

标签: javascript jquery ajax get request

我正在尝试编写一个函数,该函数将从本地托管的api返回数据,以便我可以在使用var baseUrl ='http://localhost:3000';的同时调用该函数来获取更新的数据。

这是我的获取请求:

var baseUrl = 'http://localhost:3000';
function getData(){
    $.ajax({
        type: "GET",
        url: baseUrl + "/jobs", 
        data: "{}",
        success: function(data){
            console.log(data);   
            return data;
        },
        dataType: 'json'
    });

}

以下是将请求的响应设置为其他文件中的变量的示例:

var myVariable = getData();

当我尝试打印myVariable时,它返回为未定义。有没有办法获取返回的json对象,以便可以在程序中使用它?

1 个答案:

答案 0 :(得分:0)

$。ajax是异步。这意味着,在请求等待响应的同时,其他JavaScript代码也会运行,因此用户不必等待。 (如果代码等待响应,我们称其为阻塞线程。否则为 non-blocking )。作为解决方案,您将必须编写一些异步代码和回调函数

var baseUrl = 'http://localhost:3000';
function getData(){
$.ajax({
    type: "GET",
    url: baseUrl + "/jobs", 
    data: "{}",
    success: function(data){
        // call the 'callback function'
        myCode(data);
        // the return statement would only return this functions, not the $.ajax method
    },
    dataType: 'json'
});

}

function myCode(data) {
    // use data
}