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.

    评论

报告相同问题?