Running a function by typing in URL - Javascript [duplicate]
Possible Duplicate:
Running a function by typing in URL
On my website I have several functions that when a hyperlink is clicked on example.php page, the main content changes accordingly. Now I want to direct people from a single URL to that example.ph开发者_开发问答p page with the function already called. Example - www.example.com/example.php?AC ( which will call a function named AC and the content changes before the page loads)
I had already asked the same question, but forgot to tag javascript and tagged php.
Thanks in advanced.
You can use JavaScript to get the querystring, and call the functions accordingly.
How to get querystring in JavaScript: JavaScript query string
What I would do is read the query string by using something like this to figure out if the key is there
function doesKeyExist(key) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
return qs != null;
}
Then
if(doesKeyExist(AC)) {
// run my code
}
You could do:
var query = document.location.search;
var func = window[query];
if (func && typeof(func) == "function")
func();
<script language="javascript">
var k = document.location.toString().split('?');
if(k.length > 1)
{
if(k[1] == "AC")
AC();
}
</script>
You can add a window.onload handler, check the query string of the page and act accordingly. For example:
<html>
<body>
<script>
function handleOnload()
{
if(location.search == "?AC")
alert("the query string is " + location.search);
}
window.onload=handleOnload;
</script>
</body>
</html>
You run a JS funciton like this.
<script type="text/javascript">
function test()
{
alert('test');
}
</script>
Now if you type javascript:test()
in the url it will execute test function.
精彩评论