Ajax - 在"成功"之后转到另一个页面从那里的url中检索用户id

Zyg*_*Zyg 2 javascript ajax rest json

var JSONonj = {"name": "James","age":"25"};
var data = "This data i would like to retrieve and print in the main.html page after success call in ajax.";

$.ajax({
        url: "/user",
        type: "POST",
        data: JSONobj,
        dataType: "json",
        success: function() {
            window.location.href = "main.html";
        },
        contentType: "application/json"
});
Run Code Online (Sandbox Code Playgroud)

这是交易.成功之后我想重定向到main.html,当我到达那里时,我想在那里检索和打印数据变量.

重定向工作正常.但我无法在那里收到数据.

LeG*_*GEC 8

有两种主要方法可以实现这一目标:

  1. 以某种方式将数据发送到服务器(请参阅其他答案,了解可能的方法)
  2. 使用浏览器localStorage:

    success: function() {
        localStorage.setItem('myMainKey', data);
        window.location.href = "main.html";
    }
    
    // in main.html's javascript :
    var data = localStorage.getItem('myMainKey');
    if (data !== undefined) {
        //do something
    }
    
    Run Code Online (Sandbox Code Playgroud)

注意:如果要存储和检索完整的javascript对象,则必须使用JSON.stringify()/ JSON.parse()存储/检索它.