如何在ajax成功之后将变量传递给JS代码的HTML页面?

时间:2014-02-09 05:56:52

标签: javascript jquery html ajax

考虑ajax请求:

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如何抓住它?

非常感谢

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分:1)

在成功部分编辑代码js:

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