检查window.location.href.indexOf是否'不起作用

Check for window.location.href.indexOf doesn't work

本文关键字:不起作用 是否 indexOf window location href 检查      更新时间:2023-09-26

我试图每秒调用服务器上的一个页面,仅当用户所在的当前页面是Create页面或Edit页面时。但这个代码不起作用:

function sessionRefresh(){
var remoteURL = '/path/to/file';
    $.get(remoteURL,  function(data){
      setTimeout('sessionRefresh()',1000);
    });
}
if(window.location.href.indexOf("/create" != -1) || window.location.href.indexOf("/edit" != -1)) {
    setTimeout('sessionRefresh()',1000);
}

sessionRefresh()函数正在所有页面上运行。但我只希望它在URL中有/create/edit的情况下运行。需要注意的是,我不会在生产服务器上每秒都得到这个文件。这只是为了测试。

我如何重写它,以便只在那些创建和编辑页面上调用该函数?

您犯了复制粘贴拼写错误,请尝试

if(window.location.href.indexOf("/create") != -1 || window.location.href.indexOf("/edit") != -1) {

而不是

if(window.location.href.indexOf("/create" != -1) || window.location.href.indexOf("/edit" != -1)) {

更换

if(window.location.href.indexOf("/create" != -1) || window.location.href.indexOf("/edit" != -1)) {
setTimeout('sessionRefresh()',1000);

}

带有

if(window.location.href.indexOf("/create")!=-1|| window.location.href.indexOf("/edit")!=-1){setTimeout('sessionRefresh()',1000);}