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

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?

图片转代码服务由CSDN问答提供 功能建议

                    

对于我的Phonegap / Cordova项目,我试图使用以下功能来处理所有的ajax调用:

 函数requestData(action,id){
     var data = {
         user_id:localStorage.getItem('user_id')
     };
     if(操作=='feed_load_feedings'||操作=='feed_add_load_menu_weight'||操作=='feed_add_load_menu_supps'){
         data.id = id;
     }
     $ .ajax({
         类型:“ post”,
         网址:“ http://_______.com/file.php?” +操作,
         异步:错误,
         crossDomain:是的,
         数据:数据,
         beforeSend:showLoader,
         错误:handleError,
         成功:成功
     });
 }
 函数showLoader(){
     console.log('showLoader已发射')
     $('body')。prepend('

德语单词... '); } 函数handleError(data){      console.log('handleError被触发')      $('#loading')。remove();      $('body')。prepend('

Fout tijdens het laden van de gegevens ... ');      返回false; } 函数handleSuccess(data){      console.log('handleSuccess已触发')      $('#loading')。remove();      if(typeof data!=='object'){          $('body')。prepend('

gegevens对象中的异常... ');          返回false;      }      否则if(data.length == 0){          返回0;      }      其他{          返回数据;      } }

这不仅处理请求,而且还处理错误。

如果一切正常,它将返回数据。 但是使用这个:

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

 

在控制台中提供此功能

  showLoader被触发
 POST http://_______.com/file.php?feed_load_feedings
 处理成功
 未定义
  

 

在POST请求中,我可以看到该数据已被调用并且可以。 但是,它没有放入变量中。 我认为向我的ajax调用添加 async:false 可以防止这种情况。 我要监督什么?     

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • weixin_33726943
    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.

    点赞 评论
  • weixin_33716154
    weixin_33716154 2016-01-23 07:10

    The reason behind returning undefined is pretty obvious since requestData function doesn't return anything which means it indirectly returns undefined

    The flow of the ajax is asynchronous, so returning anything in the function requestData won't work. You need to pass callback function in function calling and execute it in the success/ error handlers.

    $(function() {
        requestData('herd_load_herds', 'someid', function(err, data){
          if(err){
            console.log("error");
            console.log(err);
          }else{
            console.log("success");
            console.log(data):
          }
        });    
    });
    

    in AJAX:

    function requestData(action, id, callback) {
        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: function(error){
                  handleError(error, callback);
                },
                success: function(data){
                  handleSuccess(data, callback);
                }
            });
    }
    

    In handler:

    function handleSuccess(data, next) {
        console.log('handleSuccess fired')
        $('#loading').remove();
        if( typeof data !== 'object' ) {
            $('body').prepend('<p id="error">Fout in gegevens object...</p>');
            next(undefined, false);
        }else{       
          next(undefined, data);
        }
    }
    
    function handleError(err, next) {
        console.log('handleError fired')
        $('#loading').remove();
        $('body').prepend('<p id="error">Fout tijdens het laden van de gegevens...</p>');
        next(err);
    }
    
    点赞 评论

相关推荐