函数回调jquery get中的访问请求参数

函数回调jquery get中的访问请求参数,jquery,Jquery,是否可以在jquery的函数回调中访问请求参数get function doSomething() { var level; $.get('http://example.com/getLevel', { 'login': user }, function (resp) { //any way to access user or assign resp to level here? level = r

是否可以在jquery的函数回调中访问请求参数
get

 function doSomething() {
     var level;
     $.get('http://example.com/getLevel', {
         'login': user
     },

     function (resp) {
         //any way to access user or assign resp to level here?
         level = resp; //does not work here.
     });

     //at this point level is still undefined.
 }

谢谢

Ajax是异步的,这就是为什么在代码中的注释点未定义级别的原因。如果需要将响应分配到
级别
并使用该变量,则必须将该代码包含在成功处理程序中

目前,尝试使用level(在ajax调用之后编写的代码)的代码是在ajax调用返回响应之前执行的。这会导致
级别
未定义

     function doSomething() {
           var level;
           var data = {'login':user}; //assigning data outside of get invocation
           $.get('http://example.com/getLevel', data,function(resp){
               //any way to access user or assign resp to level here?
               level = resp; //does not work here.
                //at this point level is defined and should be used in the code.
            });
            //data could now be used here
      }
将让您了解我在这里所说的内容。请在线查看评论

function doSomething() {
    var level;
    var data = {
        'login': user
    };

    $.get('http://example.com/getLevel', data, function (resp) { // js dont wait (Thats why called  Asynchronous JavaScript and XML) for this request to complete and  immediately executed next line of code.This is called callback function where your code gets executed after you receice responce from AJAX call.
        level = resp;
        // you can use level here 
        callback(resp);            // // Or use callback function and pass it response once you receive it.
    });
    // Here it could be possible that your your response is no yet received so your level variable still undefined.             
}

function callback(level) {
    // use level here
}

Sry可能重复,我看不出你的代码和我的代码有什么不同。它只是将单独的变量定义为
数据
。这有助于分配
级别
?代码中的注释表示您想做两件事,访问用户或将响应分配到级别。将数据移到方法调用之外将允许您在代码的其他部分中使用
{'login':user}
。将所有
级别
相关代码保存在successhandler中,将保证为该级别分配响应。