Javascript - AJAX之后返回的项目始终未定义

时间:2017-04-21 00:14:49

标签: javascript jquery ajax return

我有这个功能:

function get_non_authorized_bulk_edit_option_values() {
        var modificable_column_names = get_write_user_values();
        alert(modificable_column_names);
}

它正在调用这个(我没有粘贴所有细节,例如xml变量内容或OnError函数):

function get_write_user_values() {
    var request = $.ajax({
                            type: "POST",
                            async: false,
                            url: "model/_get_user_groups_info_pipe.php",
                            data: xml,
                            contentType: "text/xml; charset=utf-8",
                            dataType: "json",
                            success: OnSuccess,
                            error: OnError
    });


    function OnSuccess(data,status,request) {
        var modificable_column_names = [];

        $.each(data.column_name, function(index, value) {
            modificable_column_names.push(value);
        });

        alert(modificable_column_names);

        return modificable_column_names;
    }
}

当我警告modificable_column_names数组时,它在get_write_user_values()函数中工作,但在get_non_authorized_bulk_edit_option_values()函数中没有(我得到未定义)。 我尝试使用对象或字符串而不是表,但我遇到了同样的问题。 为什么它不起作用?

PS:我有一个同步调用,因为在继续之前我绝对需要这个函数的结果(我知道它不是最好的选择)。

1 个答案:

答案 0 :(得分:0)

您实际上并没有从get_write_user_values()函数返回任何内容。此函数只是启动ajax调用并立即返回,甚至在ajax调用完成之前返回undefined。在某个阶段,将使用数据调用onSuccess函数,但是在该阶段,get_non_authorized_bulk_edit_option_values()函数已运行并处理未定义的值。您需要使用aj jquery ajax提供的promise。

x <- as.data.frame(cbind(c("rRNA modification","response to hydrogen peroxide","RNA processing","mRNA processing","rRNA modification","response to hydrogen peroxide","RNA processing","mRNA processing"),c("DE","DE","DE","DE","AS","AS","AS","AS"),c(3.42,2.78,1.37,0.83,0,2.87,4.05,8.63),c(4.62e-08,4.32e-03,9.00e-02,8.60e-01,0,5.30e-01,5.67e-03,6.72e-03)))
colnames(x) <- c("go","set_gene","factor","p.value")
x$factor<- as.numeric(as.character(x$factor))
x$p.value <- as.numeric(as.character(x$p.value))
library(ggplot2)
plot1 <- ggplot(x,aes(x=set_gene,y=go,size=factor,fill=ifelse(p.value>0.1,0.1,ifelse(p.value<0.0001,0.0001,p.value))))
plot1 <- plot1+ geom_point(shape=21,size=x$factor*4)
library(scales)
plot1<- plot1 + 
scale_fill_gradientn(colours=c("red","orange","yellow","grey90"),values = 
rescale(c(0.0001,0.001,0.01,0.1)),limits=c(0.0001,0.1))
plot1

这将确保get_non_authorized_bulk_edit_option_values中的代码将等待来自ajax调用的数据在执行其警报之前到达。

如果您不熟悉jquery promises,请阅读https://api.jquery.com/deferred.then/