简体   繁体   English

将数据从JS页面发送到没有表单或URL的HTML页面

[英]Sending Data from a JS page to an HTML page without Form or URL

I want to send a variable from JavaScript to another HTML page and be redirected to that page, but I can't use forms because the first page is purely in JavaScript and a .js file so I can't declare a form. 我想将一个变量从JavaScript发送到另一个HTML页面并重定向到该页面,但我不能使用表单,因为第一页纯粹是用JavaScript和.js文件,所以我不能声明一个表单。 I also can't use the URL as my data is too big. 我也无法使用URL,因为我的数据太大了。 What are other options? 还有什么其他选择? Every tutorial I've found uses either forms or the URL. 我发现的每个教程都使用表单或URL。 Is there an alternative? 还有其他选择吗?

Based on this answer , I used the following code: 根据这个答案 ,我使用了以下代码:

function post(array) {
    var method = "post"; 
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", "helloworld.html");

    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "array");
    hiddenField.setAttribute("value", array);

    form.appendChild(hiddenField);

    document.body.appendChild(form);
    form.submit();
}

and I call post(parameter) in another method. 我在另一个方法中调用post(参数)。

It successfully redirects to helloworld.html, but how can I get the variable that I passed? 它成功地重定向到helloworld.html,但是如何获得我传递的变量?

You can make an HTTP request from JavaScript: 您可以从JavaScript发出HTTP请求:

// jQuery
$.get("demo_test.asp", function(data, status){
        // do something
});

jQuery documentation is located here jQuery文档位于此处

You can use jQuery ajax API and send the data through POST request. 您可以使用jQuery ajax API并通过POST请求发送数据。 See more: here or here 查看更多: 此处此处

Edit: oops, I didn't notice that you don't have any server side handler enabled. 编辑:oops,我没有注意到你没有启用任何服务器端处理程序。 In that case, if you do not want to use forms you can handle get/url parameters with jQuery.param() or use some routing enabling library. 在这种情况下,如果您不想使用表单,可以使用jQuery.param()处理get / url参数或使用某些路由启用库。

You can save the data in the localStorage and if the second page is in the same domain. 您可以将数据保存在localStorage ,如果第二个页面位于同一个域中。 The data has to be string. 数据必须是字符串。

Page One: 第一页:

function sendData(){
    localStorage.setItem("data", data);
    location.href = "helloworld.html";
}

Save the data. 保存数据。

Page Two: 第二页:

function onLoad(){
    var data = storage.getItem("data");
}

Read the data. 阅读数据。

Optional: You could also create a JSON Object and save it with the function JSON.stringify 可选:您还可以创建JSON对象并使用函数JSON.stringify保存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM