简体   繁体   中英

How to pass URL variables to javascript in PHP

I need to take a URL variable into a PHP page, and then later pass it into some javascript that's in HTML later in the page. Here's where I need to use the variable:

function dosubmit( ) {
new Ajax.Updater( 'result', 'dial.php', { method: 'post' , parameters: $('dialer').serialize() } );
$('dialer').reset();
}

the URL variable is formatted as dialout.php?ext=1234. It is stored in PHP as $ext. result is the div that returned html will be placed in, and dialer is a form that a user would enter a phone number into; I need to pass it along with the $ext variable to dial.php. My thought was to concatenate the two, as

var ext = "<? $uext ?>";
var par = $('dialer').serialize();
var url = par;

and then using url in place of $('dialer').serialize() . This does not work, though; dial.php reports never gets the ext variable. What's the best way to move a URL variable into PHP, then into js, then post it back to PHP? I apologize in advance if I've mis-explained something, this is all new to me.

Thanks!

You have the right idea, but you need to use a command like print or echo to populate the variable:

var ext = "<? echo $uext ?>";

Otherwise $uext by itself as a PHP statement effectively does nothing.

Also, you need to include the ext variable into your parameter list. Your current code as it stands doesn't make any further references to ext after it is populated:

var par = $('dialer').serialize();
par += '&ext=' + ext;

I can't understand fully what you want, but for similar cases I've been using: from URL to PHP GET method, from PHP to JS JSON with jsonencode() (ajax), and finally a POST or GET in ajax to a php page.

There should be better ways to do it though.

At looking again at your example I've seen that you use php inside javascript, but you lack an echo, so it should be like this:

var ext = "<? echo $uext; ?>";

If it's just a get parameter as you mentioned, there's no reason you can't access it directly in JavaScript. Since it's seems you're using jQuery, you may want to take a look at the Query String Object plugin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM