[英]How do I pass form data from one HTML page to another HTML page using ONLY javascript?
[英]How to pass data from one HTML page to another HTML page using JQuery?
我有两个以这种方式在父子关系中工作的HTML页面:
第一个具有一个按钮,该按钮执行以下两项操作:首先,它通过AJAX调用从数据库请求数据。 其次,它将用户引导到具有所请求数据的下一页,JavaScript将对其进行处理以填充第二页。
我已经可以通过ajax调用获取数据并将其放入JSON数组中:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
我假设在第二页上,一个“文档就绪”的JavaScript函数可以轻松地处理所有数据的传递JSON对象的捕获。 最好的测试方法是使用alert("My data: " + json.my_data.first_name);
在文档准备功能中查看是否已正确传递JSON对象。
我只是不知道执行此操作的可靠方法。 我已经阅读了论坛,并且知道使用window.location.url
加载第二页的基本知识,但是传递数据完全是另一回事了。
会话cookie可能会解决您的问题。
在第二页上,您可以直接在带有Server-Script标签或站点document.cookie的cookie中进行打印。
在以下部分中,再次在Json中转换Cookies
怎么样?
免责声明:这很糟糕,但是这里有:
首先,您将需要此功能(我之前对此进行了编码)。 此处的详细信息: http : //refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
它将请求参数转换为json表示形式。
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
接下来,在您的成功处理函数中:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
在下一页上,调用getParameterMap。
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
希望这会有所帮助(有一些额外的说明可以使事情变得很明显)。 (记住,正如人们指出的那样,这很可能是错误的方法)。
这是我有关两个html页面之间进行通信的帖子,它是纯JavaScript并使用cookie: 浏览器选项卡/窗口之间的JavaScript通信
您可以在那里重复使用代码以将消息从一页发送到另一页。
该代码使用轮询来获取数据,您可以根据需要设置轮询时间。
警告:这仅适用于单页面模板,其中每个伪页面都有其自己的HTML文档。
您可以通过手动使用$.mobile.changePage()
函数在页面之间传递数据,而不是让jQuery Mobile为您的链接调用它:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
这是有关此文档: http : //jquerymobile.com/demos/1.1.1/docs/api/methods.html
您也可以简单地将数据存储在下一页的变量中。 这是可能的,因为jQuery Mobile页面存在于同一DOM中,因为它们是通过AJAX引入DOM的。 这是我不久前发布的答案: jQuery Moblie:传递参数并动态加载页面内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.