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

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

问题描述

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

 < body onLoad =sndReq ( '96')> 

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



现在我的问题是:如果我想发送一个链接到客户端,直接打开一个特定的项目,所以他不必浏览网站?



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



我该如何实现这一点?我希望能够通过URL打开特定的项目,但是如果没有任何东西通过URL传递,它应该始终打开项目96.



预先感谢您。



Cletus

解决方案

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

  var queryStr = window.location.search;然后,你可以去掉并将每个查询字符串参数拆分为一个数组: 

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

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

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

$ / code>

onload ,那么现在可以使用这个参数:

  sndReq(params.sndReq); 

确保代码在头部的脚本中运行 code>,以便在执行 onload 之前计算它。


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 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?

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)

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.

Cletus

解决方案

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];
}

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

sndReq(params.sndReq);

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天全站免登陆