简体   繁体   中英

how to pass a php variable in a href link with javascript window open

The code below works to call a JS window.open

<?
$facebookID = "ID";
$parameters = array(
                'app_id' => 'app_ID',
                'to' => $facebookID,
                'link' => 'link',
                'redirect_uri' => 'my_url'
                );
$url = 'http://www.facebook.com/dialog/send?'.http_build_query($parameters);
echo '<script type="text/javascript">window.open('.json_encode($url).');</script>';
?>

CODE ABOVE WORKS... it opens a window with the facebook send dailog

But how can I implement this in a link to call this window on click only with the specefic facebook ID...

I build my page with multiple faceboook ID like this:

<?
// CODE ABOVE.....
while($row = $stmt->fetch())
{ 
     $facebookID = $row['facebookID'];

     $parameters = array(
                'app_id' => 'app_ID',
                'to' => $facebookID,
                'link' => 'link',
                'redirect_uri' => 'my_url'
                );

     $url = 'http://www.facebook.com/dialog/send?'.http_build_query($parameters);

    ?>

    <a href="#">ON CLICK CALL the JavaScript for this specefic Facebook User</a>
    <? 
    }
    ?>

What should be my href="....." ? I tried the following, but it didn't work... I guess it's because of the php variable inside the window.open...

<a href="javascript: void(0)" onclick="window.open('.json_encode($url).');" </a>

thanks

尝试这个:

echo '<a href="#" onclick="window.open(' . json_encode($url) . '); return false;">ON CLICK CALL the JavaScript for this specefic Facebook User</a>';

You cannot use json encode inside of window.open with double quotes in your attributes because the json_encode will add double quotes to your code.

在此处输入图片说明

(see that the attribute onclick is "fighting" with your double quotes from window.open)

If you invert the single quotes to double quotes, it will work properly using json_encode.

$url = 'http://test.com';
echo "<a href='javascript: void(0)' onclick='window.open(" . json_encode($url) . ");'>Test</a>";

(because the json encode will add double quotes and your attributes have single quotes.)

Another way to do it (that i recommend) is remove the json_encode and put single quotes inside your php.

$url = 'http://test.com';
echo '<a href="javascript: void(0)" onclick="window.open(' . '\'' . $url . '\'' . ');">Test</a>';

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