2014-02-09 41 views
0

考慮Ajax請求:如何在ajax成功後將變量傳遞給JS代碼的HTML頁面?

var idNumber = $("#Field_1").val(); 
var servletUrl = "someURL"; // some url goes here 

$.ajax({ 
    url: servletUrl, 
    type: 'POST', 
    cache: false, 
    data: { }, 
    success: function(data){ 
     alert(data); 
     window.location = "./replyToYou.html"; 
    } 
    , error: function(jqXHR, textStatus, err){ 
     alert('text status '+textStatus+', err '+err + " " + JSON.stringify(jqXHR)); 
    } 
}); 

我怎麼能傳球,成功idNumberreplyToYou.html,我怎麼能抓住它replyToYou.html

非常感謝

回答

1

你有不同的解決方案:

1 - 首先是使用的queryString:

success: function(data){ 
    alert(data); 
    window.location = "./replyToYou.html?idNumber=" + idNumber; 
} 

然後使用此功能查詢字符串讀它(我使用它作爲查詢字符串幫手其原始創建於POST):

function getParameterByName(name) { 
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); 
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), 
    results = regex.exec(location.search); 
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); 
} 
getParameterByName("idNumber"); 

2-另一種選擇是使用localStorage

success: function(data){ 
    alert(data); 
    localStorage.setItem("idNumber",idNumber); 
    window.location = "./replyToYou.html"; 
} 

,並在其他頁面得到它就像:

localStorage.getItem("idNumber") 
+0

糾正我,我錯了,但是使用你建議的'1st'方法會導致用戶在地址欄中看到傳遞的細節? – ron

+0

@ron:這是正確的,但你可以使用Base64或其他,來編碼它。我自己通常採用第二種解決方案。 –

+0

是的,我在瀏覽器選項卡中看到類似這樣的內容:'/register_replyToYou.html?idNumber = 44444444444444444444' – ron

1

編輯代碼JS在成功的部分:如果

success: function(data){ 
    alert(data); 
    window.location.href = "./replyToYou.html?idNumber=" + idNumber; 
} 
+0

這是一個HTML頁面,所以你必須有一些方法從URL字符串獲取IDNumber。 –

相關問題