Ajax调用$ .ajax()。完成

时间:2016-10-20 02:49:27

标签: javascript jquery ajax

我有jQuery ajax函数的问题。我使用API​​提供用户和RBAC管理。根据设计,这是分离的功能,所以当我创建一个用户并为其分配一个角色时,我应该调用两个请求 - 首先我发送'create user'并返回一个{“success”:“true”,“id”:“ [id nuber]“}然后我发送'assign role'和params,如”{“item”:“RoleName”,“user_id”:“[id from previous request]”}“。 有一些对象“api”有一些使用API​​的方法。这是一个简单的包装器,可以敲击www.myurl.api /并返回json。因为它可能需要很长时间api对象方法需要一个将成功运行并失败的处理程序。如果api现在正在运行请求,那么api.ready == false,否则api.aready == true。上次请求的结果存储在api.data中作为对象。

问题是,当两个API请求级联时,结果未保存在api.data中,例如:

api.send(params, //params is json for user creation
    function(){  //handler on this request result
        ...      //creating another parms for assignment from api.data
        api.send(params2, function(){//handler that works if api coorectly creates a new user
            ... //here i try send a request with params and it fails  
        })
}

);

api.send方法的代码:

send: function (entity, request, params, method, handler){
    if (!method)
        method='POST';
    if (request.toLowerCase()=='get')
        request = '';
    if (request)
        request += '-';
    api.data = null;
    params.apiKey = api.key;
    api.ready = false;
    api.handler = handler;
    $.ajax({
        url: this.url+request+ entity,
        method: 'GET',
        data: params
    }).complete(function(msg) {
      api.data = JSON.parse(msg.responseText);
      if (api.data[0] && api.data[0].meta)
          api.data.forEach(function (element, index, array){
              element.meta = JSON.parse(element.meta)
          });
      api.ready = true;
      api.handler.call();
    });
}

这是调用创建新用户的函数

function createUser(){
    validateCreateForm();
    if (!createValidated )
        return;
    var values = {
      "username": $('#inputUsername').val(),
      "password": $('#inputPassword').val(),
      "comment": "Added by "+adderUsername
    };

    api.send('users','add', values, 'POST', function () {
        if (api.data.success="true"){

//===========all in this if works ONLY if api works succesfully
//===========and api.data.id is exist and correct

            message("success", "Was created username " + values.username);
            $('#inputUsername').val('');
            $('#inputPassword').val('');

 //==========Problem is here
            id = api.data.id; //in this var stores id
            console.log('api.data.id is ' + id);//undefined, should be some int.
 //if write something like id=42 rights will be correcttly assigned for user with id 42 
 //================================================================

            if (!$('#inputRole').val())
               return;
            api.send('assignments',
                     'add',
                     {
                       "user_id": id,
                       "item_name": $('#inputRole').val()
                     },
                      'POST',
                      function () {
                          if (api.data.success="true"){
                              message("success", "Account was created and permissions granted");
                          }
                          else {
                              message("success", "Inner error. Please, try again later.");
                          }
                      }
                    );
        }
        else {
            message("danger", "Inner error. Please, try again later.");

    }
  );
}

0 个答案:

没有答案