简体   繁体   中英

PHP Variable in Echoing JavaScript

I have an php script that is echoing JavaScript, in the JavaScript there are PHP variables

echo '<script type="text/javascript"> 
     FB.init({
    appId: "myid",
    channelUrl: "//mysite/channel.html",
    status: true, // check login status
    cookie: true, // enable cookies to allow the server to access the session
    xfbml: true // parse XFBML
});
FB.getLoginStatus(function (response) {
    if (response.status === "connected") {
        FB.api("me/bookvote:download", "post", {
            book: "<?php echo "http://mysite/auction_details.php?name=$item_details["name"]&auction_id=$item_details["auction_id"]";?>",
            fb:explicitly_shared = "true" //? Is syntactically valid but creates a global
        }, //Missing a , here?

However, I am still getting:

Uncaught SyntaxError: Unexpected identifier for book: http://mysite.xom/auction_details.php?name=$item_details["name"]&auction_id=$item_details["auction_id"]";?>",

What should I do?

I can spot multiple issues:

  • You try to print variables inside of single quotes. They won't be parsed, you need double quotes, or better yet, HEREDOC, or even better yet , don't use echo to print HTML/JavaScript.
  • You try to use additional <?php ?> tags inside of your echo. That would obviously not work.

Try this. I have removed the echo. Note that the larger PHP tag ends there.

?>
<script type="text/javascript"> 
     FB.init({
    appId: "myid",
    channelUrl: "//mysite/channel.html",
    status: true, // check login status
    cookie: true, // enable cookies to allow the server to access the session
    xfbml: true // parse XFBML
});
FB.getLoginStatus(function (response) {
    if (response.status === "connected") {
        FB.api("me/bookvote:download", "post", {
            book: "<?php echo "http://mysite/auction_details.php?name=$item_details["name"]&auction_id=$item_details["auction_id"]";?>",
            fb:explicitly_shared = "true" //? Is syntactically valid but creates a global
        }, //Missing a , here?

更改此行:

book: "http://mysite/auction_details.php?name=' . $item_details["name"] . '&auction_id=' . $item_details["auction_id"] . '",

Those variables never got converted to their actual values that are supposed to be used. Try breaking that string into multiple parts via concatenation.

You'll want to end your echo quote so it's like this:

echo '<script type="text/javascript"> 
....
            book: "http://mysite/auction_details.php?name=' . $item_details["name"] . '&auction_id=' . $item_details["auction_id"] . '",
....

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