简体   繁体   English

如何防止window.onload自身重复

[英]How to prevent window.onload from repeating itself

I am trying to execute a js action that automatically sends informations to the URL for future use with php. 我正在尝试执行一个js操作,该操作会自动将信息发送到URL,以供将来与php一起使用。 To do so, I added a "onload" event on the window object and modified the URL in the listener. 为此,我在窗口对象上添加了“ onload”事件,并在侦听器中修改了URL。 This is what it looks like so far: 到目前为止是这样的:

window.addEventListener("load", function() {
    window.location = "?test=test";
}, false);

When I load the page, the URL changes, but this is repeated over and over until the browser crashes. 当我加载页面时,URL会更改,但是会不断重复直到浏览器崩溃。 I was just wondering if there was a way to only execute it once. 我只是想知道是否有一种方法只能执行一次。

重定向之前,请检查您是否已经在该页面上。

在URL上添加一个简单的标志,如下所示: window.location = "?test=test&second=true";

As suggested in How can I get query string values in JavaScript? 我如何在JavaScript中获取查询字符串值中所建议的那样

Write a function to check get the URL params in JS GetQueryStringParams() 编写函数以检查是否在JS中获取URL参数GetQueryStringParams()

Then as suggested by others pass a send param in while reload 然后按照其他人的建议,在重载时传递发送参数

window.location = "?test=test&second=true"; window.location =“?test = test&second = true”;

Use the function in JS to check if you have a URL query string second and if its not there then reload the page 使用JS中的函数检查是否有第二个URL查询字符串,如果没有,则重新加载页面

If you don't want to use AJAX, and don't want to write JS functions to parse query strings, why not a simple: 如果您不想使用AJAX,并且不想编写JS函数来解析查询字符串,那么为什么不那么简单:

<?php if(!isset($_GET['test'])): ?>
<script>
   window.addEventListener("load", function() {
       window.location = "?test=test";
   }, false);
</script>
<?php else: ?>

 <!--No JS written on the page, so no redirect -->

<?php endif;?>

But you really should look into AJAX, try using some JS framework like jQuery to help you in the process: http://api.jquery.com/jquery.ajax/ 但是您确实应该研究AJAX,尝试使用jQuery之类的JS框架在此过程中为您提供帮助: http : //api.jquery.com/jquery.ajax/

if you want to pass variables do this: 如果要传递变量,请执行以下操作:

<?php
    if(!isset($_GET['page'])){ //this line check if the variable field is available 
    $a = "Blank";
    }else{
    $a = $_GET['page'];
    }
?>

that is it. 这就对了。

You could just erase the onLoad method once it's run, like so: 您可以在onLoad方法运行后立即将其擦除,如下所示:

<script>
function doLoadStuff()
{
    doSomeStuff();

    //Clear onLoad contents
    body.onLoad = function() {};
}
</script>
<body onLoad="doLoadStuff();">MyContent</body>

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

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