在窗口加载时通过 URL 将值传递给 JS 函数 [英] Passing value to JS function through URL on window load

查看:39
本文介绍了在窗口加载时通过 URL 将值传递给 JS 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面 http://www.dinomuhic.com/2010/index.php 在页面开头使用 onLoad 调用加载 Showreel,如下所示:

my page http://www.dinomuhic.com/2010/index.php loads the Showreel at the start of the page using an onLoad call in body like this:

<body onLoad="sndReq('96')">

96 是 SQL 库中 showreel 的 ID.JS 函数sndReq"是使用 JQuery 的 AJAX 调用,它打开请求的项目并将其显示在主窗口中.

96 is the ID of the showreel in the SQL Library. The JS function "sndReq" is an AJAX call using JQuery which opens the requested item and displays it in the main window.

现在我的问题是:如果我想将链接发送给直接打开特定项目的客户,这样他就不必浏览网站怎么办?

Now my question: What if I want to send a link to a client which opens a specific item directly so he does not have to navigate through the site?

类似于 http://www.dinomuhic.com/2010/index.php?sndReq=234(当然现在不起作用,只是打开showreel,可能是因为body标签中的onLoad覆盖了它)

Something like http://www.dinomuhic.com/2010/index.php?sndReq=234 (which of course doesn't work now and just opens the showreel, probably because the onLoad in the body tag overrides it)

我该如何实现?我希望能够通过 URL 打开特定项目,但如果没有通过 URL 传递任何内容,它应该始终打开项目 96.

How can I implement this? I want to be able to open specific items by URL but if nothing is passed through the URL it should always open item 96.

先谢谢你.我确定这很容易,我只是看不到它.

Thank you in advance. I'm sure its pretty easy I just can't see it.

克莱图斯

推荐答案

您需要解析查询字符串.我发现处理查询字符串的最简单方法是执行以下操作.首先,您需要从 URL 中提取查询字符串:

You need to parse the query string. I find the easiest way to deal with the query string is to do the following. First, you need to extract the query string from the URL:

var queryStr = window.location.search; // will give you ?sndReq=234

然后,你可以去掉?并将每个查询字符串参数拆分成一个数组:

Then, you can strip out the ? and split each query string parameter into an array:

var paramPairs = queryStr.substr(1).split('&');

现在您可以构建组成查询字符串的名称/值对的哈希表对象:

Now you can build a hash table object of the name/value pairs making up the query string:

var params = {};
for (var i = 0; i < paramPairs.length; i++) {
    var parts = paramPairs[i].split('=');
    params[parts[0]] = parts[1];
}

在您的 onload 中,您现在可以这样使用参数:

In your onload, you can now use the parameter thusly:

sndReq(params.sndReq);

确保代码在文档的 head 中的脚本中运行,以便在执行 onload 之前计算它.

Make sure that the code is run within a script in the head of your document so that it's computed before the onload is executed.

这篇关于在窗口加载时通过 URL 将值传递给 JS 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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