Getting data from URL (like php's $_GET) for jQuery/Ajax?
What I'm wanting to do is take a URL like myurl.com/page.php?data1=x&data2=y&data3=z and get each piece of data and use it in a jQuery function. Is there any built in way to do that?
To clarify, when I navigate to (say, pasting the url into the address bar, or going to it via a 开发者_运维百科bookmark) I want jQuery to do something with that data.
As a bonus, if it also includes something to check if the data is set to something, that would be great.
You're looking for how to get values from the query string. Here's pretty much the same question:
How can I get query string values in JavaScript?
A quick way to do it would be if your javascript code is embedded in a php file (not an external link to a .js file), you could just do a PHP print right in between your <script></script>
tags. It would work with bookmarks and pasting the URL to the address bar.
For example:
<script type="text/javascript">
var get_var;
get_var = <? print $_GET['varname']; ?>;
// some jQuery code here
</script>
This should only be used as a proof of concept. This is vulnerable to XSS attacks, and should not be used in production. This list of XSS prevention techniques is a good place to start (but outside the scope of the OP's question).
Perhaps a plugin like jQuery.url.js would work or maybe Url parser.
精彩评论