weixin_33696106 2016-01-23 06:48 采纳率: 0%
浏览 94

jQuery ajax调用变量

For my Phonegap/Cordova project I'm trying to handle all ajax calls with the following functions:

function requestData(action, id ) {
    var data = {
        user_id: localStorage.getItem('user_id')
    };
    if( action == 'feed_load_feedings' || action == 'feed_add_load_menu_weight' || action == 'feed_add_load_menu_supps' ) {
        data.id = id;
    }
    $.ajax({
        type: 'post',
        url: 'http://_______.com/file.php?'+action,
        async: false,
        crossDomain: true,
        data: data,
        beforeSend: showLoader,
        error: handleError,
        success: handleSuccess
    });
}
function showLoader() {
    console.log('showLoader fired')
    $('body').prepend('<p id="loading">De gegevens worden geladen...</p>');
}
function handleError(data) {
    console.log('handleError fired')
    $('#loading').remove();
    $('body').prepend('<p id="error">Fout tijdens het laden van de gegevens...</p>');
    return false;
}
function handleSuccess(data) {
    console.log('handleSuccess fired')
    $('#loading').remove();
    if( typeof data !== 'object' ) {
        $('body').prepend('<p id="error">Fout in gegevens object...</p>');
        return false;
    }
    else if(data.length == 0 ) {
        return 0;
    }
    else {
        return data;
    }
}

This handles the request, but also the error handling.

If everything is alright, it should return the data. However using this:

$(function() {
    var herd = requestData('herd_load_herds');
    console.log(herd):
});

Gives this in the console:

showLoader fired
POST http://_______.com/file.php?feed_load_feedings
handleSuccess fired
undefined

In the POST request I can see that the data is called and okay. However it isn't put into the variable. I thought that adding async: false to my ajax call would prevent that. What am I overseeing?

  • 写回答

2条回答 默认 最新

  • weixin_33726943 2016-01-23 07:00
    关注

    Your code is working perfectly fine. JavaScript functions without a return value return undefined by default. Your function requestData has no return <someValue> statement and so returns the default undefined.

    If you want to save the data, you need to save it in the success callback.

    My advise is to not try and hack around with async: false. Just do everything async and respond to callbacks appropriately.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?