I have a PHP page with where I also use jQuery UI functionality. User drags Item from left panel into a box on the right. After it is dropped a dialog appears. If user clicks the first button he/she is redirected to a URL. I need to be able to change URL based on a user.
I can get the URL into a var or $_SESSION but I can't figure out how do I change it inside my JS function?
Here's the DEMO (drop item into box to get dialog).
UPDATE:
Below开发者_JS百科 are all valid suggestions, however, my problem is that I have most of JS functions in external JS file (dragdrop-client.js).
I have added new var to my main PHP file
var endURL = "http://google.com";
but how do make my function checkLaunchpad() use it?
There are a number of different ways to do it, but often it is as simple as:
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
Where $url is the url you want them to go to (perhaps '/boxes.php?uid='.$_SESSION['id'];?) That will translate to:
<script type="text/javascript">var myURL = 'http://whatever.and.stuff'</script>
EDIT
You just asked how you would have a function declared on an external JS page use the variable.
Well, fortunately, JS doesn't care when you declare the variable, so long as it has some value before you use it. And, if it doesn't have a value then, it will supply undefined
;. This means you can declare functions which rely on global variables which won't exist for another three or for seconds/minutes/years/eons/whatever.
Additionally, the earlier a script tag is on a page, the earlier it will be evaluated -- a variable declared in the first tag will exist when the second js file loads.
So, if you want to have the above work as expected you have two options.
You could define the variable as the first script tag in the body of the page (thus, it is defined before checkLaunchpad
is.
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
<script type="text/javascript" src="path/to/js"></script>
Or, if checkLaunchpad
isn't called until after the body has loaded, you can place the definition anywhere in a script tag!
Find below code to redirect users to new page
<script type="text/javascript">
var endURL = "http://google.com";
function checkLaunchpad(url) {
location.href=url;
return false;
}
</script>
<a href="javascript: void('0')" onclick="javascript: return checkLaunchpad(endURL);">Test</a>
for more reference check http://snook.ca/archives/javascript/global_variable
I would say store the url in a hidden field like:
<input id="hidUrl" type="hidden" value="<?php echo $url ?>"/>
And then change your javascript so it uses the value:
window.location = $("#hidUrl").val();
精彩评论