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.

    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条