在页面加载之间保持变量 [英] Persist variables between page loads

查看:29
本文介绍了在页面加载之间保持变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获表单的提交按钮按下情况,如果表单已提交,页面会刷新并显示一些隐藏字段.我想捕获表单之前是否已提交,如果它在重新加载时提交,我想取消隐藏隐藏字段.我试图使用全局变量来实现这一点,但是我无法使其正常工作.

I am trying to capture the submit button press of my form and if the form is submitted, the page refreshes and I show a few hidden fields. I would like to capture whether the form has been submitted before or not and if it submitted on reload, I would like to unhide the hidden fields. I was trying to use a global variable to achieve this, however I was unable to make it work properly.

这是我尝试过的:

  var clicked = false;

  $(document).ready(function() {

    $("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true;  return true;");

    if (clicked == true) {
      // show hidden fields
    } else {
      // don't show hidden fields
    }
  });

对此代码有什么问题有什么建议吗?

Any suggestions on what is wrong with this code?

推荐答案

由于 HTTP 是无状态的,每次加载页面时,它将使用您在 JavaScript 中设置的任何初始值.您不能在 JS 中设置全局变量并在再次加载页面后简单地保留该值.

As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.

有几种方法可以将值存储在另一个位置,以便在加载时使用 JavaScript 对其进行初始化

There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript

查询字符串

当使用 GET 方法提交表单时,url 会更新为查询字符串 (?parameter=value&something=42).您可以通过将表单中的输入字段设置为特定值来利用此功能.这是最简单的例子:

When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:

<form method="GET">
    <input type="hidden" name="clicked" value="true" />
    <input type="submit" />
</form>

在页面初始加载时,未设置查询字符串.当您提交此表单时,输入的 namevalue 组合在查询字符串中作为 clicked=true 传递.因此,当使用该查询字符串再次加载页面时,您可以检查按钮是否被点击.

On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.

要读取这些数据,您可以在页面加载时使用以下脚本:

To read this data, you can use the following script on page load:

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, " "));
}

var clicked = getParameterByName('clicked');

(来源)

能否使用它取决于您的表单当前的工作方式,如果您已经使用了 POST,那么这可能会出现问题.

Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.

此外,对于较大的数据集,这不是最佳选择.传递字符串没什么大不了的,但对于数组和数据对象,您可能应该使用 Web Storage 或 cookie.虽然细节因浏览器而有所不同,但 URI 长度的实际限制约为 2000 个字符

In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters

网络存储

随着 HTML5 的引入,我们还获得了 Web Storage,它允许您在页面加载时将信息保存在浏览器中.有 localStorage 可以保存更长时间的数据(只要用户不手动清除它)和 sessionStorage 仅在您当前的浏览会话期间保存数据.后者在这里对您很有用,因为您不想在用户稍后回来时将​​clicked"设置为 true.

With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.

这里我设置了按钮点击事件的存储,但你也可以将它绑定到表单提交或其他任何东西.

Here I set the storage on the button click event, but you could also bind it to form submit or anything else.

$('input[type="submit"][value="Search"]').click(function() {
    sessionStorage.setItem('clicked', 'true');
});

然后当你加载页面时,你可以检查它是否使用这个设置:

Then when you load the page, you can check if it's set using this:

var clicked = sessionStorage.getItem('clicked');

即使此值仅在此浏览会话期间保存,您也可能希望更早地重置它.为此,请使用:

Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:

sessionStorage.removeItem('clicked');

如果您想保存 JS 对象或数组,您应该将其转换为字符串.根据规范,应该可以保存其他数据类型,但这还没有在浏览器中正确实现.

If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.

//set
localStorage.setItem('myObject', JSON.stringify(myObject));

//get
var myObject = JSON.parse(localStorage.getItem('myObject'));

浏览器支持非常棒所以你应该可以安全地使用它,除非你需要支持非常旧/晦涩的浏览器.网络存储是未来.

Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.

Cookies

Web 存储的替代方法是将数据保存在 cookie 中.Cookie 主要用于读取服务器端的数据,但也可用于纯客户端数据.

An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.

您已经使用了 jQuery,这使得设置 cookie 变得非常容易.同样,我在这里使用 click 事件,但可以在任何地方使用.

You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.

$('input[type="submit"][value="Search"]').click(function() {
    $.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});

然后在页面加载时,您可以像这样读取 cookie:

Then on page load you can read the cookie like this:

var clicked = $.cookie('clicked');

在您的情况下,由于 cookie 在会话中持续存在,您需要在完成任何需要对其进行处理后立即取消设置.您不希望用户在一天后回来并且仍然将 clicked 设置为 true.

As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.

if(clicked === "true") {
    //doYourStuff();
    $.cookie('clicked', null);
}

(可以在此处找到设置/读取 cookie 的非 jQuery 方式)

(a non-jQuery way to set/read cookies can be found right here)

我个人不会将 cookie 用于记住点击状态这样简单的事情,但如果查询字符串不是一个选项,并且您需要支持不支持 sessionStorage 的非常旧的浏览器,这将起作用.您应该首先通过检查 sessionStorage 来实现它,并且只有在失败时才使用 cookie 方法.

I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.

window.name

虽然这对我来说似乎是一种可能起源于 localStorage/sessionStorage 之前的 hack,但您可以将信息存储在 window.name 属性中:

Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:

window.name = "my value"

它只能存储字符串,所以如果你想保存一个对象,你必须像上面的localStorage示例一样将它字符串化:

It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:

window.name = JSON.stringify({ clicked: true });

主要区别在于,此信息不仅会保留在页面刷新中,还会保留在不同的域中.但是,它仅限于您所在的当前选项卡.

The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.

这意味着您可以在您的页面上保存一些信息,只要用户停留在该选项卡中,即使他浏览到另一个网站并返回,您也可以访问相同的信息.一般来说,除非您需要在单个浏览会话期间实际存储跨域信息,否则我建议不要使用它.

This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.

这篇关于在页面加载之间保持变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆