1

我想从 ajax 函数中获取 jquery ajax 发布请求值到外部。我的代码是这样的,它undefined作为控制台输出返回。应该怎么修

function submit() {
    var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');

    console.log(outputFromAjax);
}

function submitViaPost(url) {

    var formData = $('form').serializeArray();

    var output;

    $.post(urlForPhp + '/' + url, formData, function (outputData) {
        output = outputData;
    });
    return output;
}

已编辑

我将代码更改为同步类型 ajax 发布请求并检查输出。但它没有改变。这是我的代码

function submit() {
    var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');

    console.log(outputFromAjax);
}

function submitViaPost(url) {

    var formData = $('form').serializeArray();

    var output;

    $.ajax({
        url: urlForPhp + '/' + url,
        data: formData,
        dataType: 'JSON',
        async: false,
        method: 'POST',
        success: function (e) {
            output =  e;
        }
    });
    return output;
}
4

2 回答 2

0

不要返回,将其作为$.post异步 回调

function submit() {
    submitViaPost('administrator/validationForInputValuesOfAddRole', function(out){ //Result comes here
      var outputFromAjax = out;
      console.log(outputFromAjax);
    });
}

function submitViaPost(url , callback) { //Added callback
    var formData = $('form').serializeArray();
    $.ajax({
    url: urlForPhp + '/' + url,
    data: formData,
    dataType: 'JSON',
    async: false,
    method: 'POST',
    success: function (e) {
        callback(e);
    }
 });
}
于 2015-05-15T07:24:11.513 回答
0

您可以使用延迟 jQuery

function submit() {
    submitViaPost('administrator/validationForInputValuesOfAddRole').then(function (outputFromAjax) {
        console.log(outputFromAjax);
    });
}

function submitViaPost(url) {
    var dfd = jQuery.Deferred();
    var formData = $('form').serializeArray();
    $.post(urlForPhp + '/' + url, formData, function (outputData) {
        dfd.resolve(outputData);;
    });
    return dfd;
}
于 2015-05-15T07:33:28.950 回答