2017-05-29 102 views
0

我發送ajax調用並從第一個ajax獲得我需要的答案,然後我想將我的結果傳遞給我的嵌套ajax,我的var(result)爲null嵌套的ajax/settimeout的樂趣,我可以通過它嗎?我錯過了什麼嗎?如何將變量從ajax傳遞給嵌套的ajax

$.ajax({ 
      url: '@Url.Action("getCustomerGuidId", "Document")', 
      type: 'POST', 
      cache: false, 
      data: { "classNum": currentclassNum}, 
      contentType:'json' , 
      dataType:'text', 
      success: function (result) { 
       alert(result);**-> is fine - not null**. 
// a or result is null when I hit the getCurrentDoc- function althought I get the data I need from getCustomerGuidId function 
       var a = result;-> tried to pass it to a new var..IDK.. I 
            thought it will help... it didn't. 
       setTimeout(function() { 
        $.ajax({ 
         type: "GET", 
         url: '@Url.Action("getCurrentDoc", "Document")', 
         contentType:'text', 
         data: a,-> here it's null 
         success: function (data) { 
         } 
        });             
       }, 2000);         
      }, 
      error: function (result) { 
       alert("fail " + result); 
      } 
     }); 
+0

在的setTimeout ,函數上下文得到了改變,這就是爲什麼a在那裏是空的。 –

回答

-1

在嵌套的AJAX您發送的PARAM名稱,而不是作爲一個參數值的方式。 所以,你可以試試下面的(變化param到您的服務器預計實際PARAM名):

$.ajax({ 
     url: '@Url.Action("getCustomerGuidId", "Document")', 
     type: 'POST', 
     cache: false, 
     data: { "classNum": currentclassNum}, 
     dataType:'text', 
     success: function (result) { 
      setTimeout(function() { 
       $.ajax({ 
        type: "GET", 
        url: '@Url.Action("getCurrentDoc", "Document")', 
        data: {param: result}, 
        success: function (data) { 
        } 
       });             
      }, 2000);         
     }, 
     error: function (result) { 
      alert("fail " + result); 
     } 
    }); 
+0

仍然無效...: - / – Damkulul

0

你可以嘗試這樣的事情將有助於值傳遞給嵌套的AJAX調用

function test(){ 
var myText = 'Hello all !!'; 

$.get({ 
    //used the jsonplaceholder url for testing 
    'url':'https://jsonplaceholder.typicode.com/posts/1', 
    'method':'GET', 
    success: function (data) { 
     //updating value of myText 
     myText = 'welcome'; 
     $.post({ 
      'url':'https://jsonplaceholder.typicode.com/posts', 
      'method':'POST', 
      //data.title is the return value from get request to the post request 
      'data':{'title':data.title}, 
      'success':function (data) { 
       alert(data.title +'\n' + myText);//your code here ... 

      } 
     }); 
    } 
}); 

}