2012-06-27 12:18
浏览 70

通过jQuery-AJAX load()函数将PHP变量作为变量传递给JavaScript

I have 2 files, main.html and search.php.

Within the main.html page, there is this piece of code :

... some code here

Within the search.phppage, there is this piece of code :

$image_id=mysql_insert_id() // getting the last ID of the last query - works perfectly

What I want to do is to echo this variable to the main.html file and store it within a JS variable called im_id that I can call through the main.html page.

I tried to do this

echo "<script type=\"text/javascript\">$im_id=".mysql_insert_id()."</script>";

but it doesn't work at all.

I found a workaround which is to store the content within a textbox like this

echo "<script type=\"text/javascript\">$(\"#textbox\").val(".$image_id.")</script>";

and then in the JScript, use


and many other methods using an "intermediary" but isn't there a straight way to set the variables directly ?

Any help would be appreciated.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dp9599 2012-06-27 12:21

    Its not working because you output $im_id=1, you should output var im_id = 1; instead.

    In your PHP:

    echo "<script type=\"text/javascript\">var im_id = ".mysql_insert_id().";</script>";

    If it still doesnt work look at the generated code, not the PHP source. Just go to view source in your browser, and use a debugger to find out whats wrong.

    解决 无用
    打赏 举报
  • drzrdc1766788 2012-06-27 12:24

    The reason it's not working is that php replaces variables inside double quotes with the value of your variable. This makes for easy templating. For more information see the variable parsing section of the php docs.

    $juice = "apple";
    echo "He drank some $juice juice.".PHP_EOL;
    // Invalid. "s" is a valid character for a variable name, but the variable is $juice.
    echo "He drank some juice made of $juices.";

    The above example will output:

    He drank some apple juice.
    He drank some juice made of .

    Either replace the double quotes with single if you want to have a variable name in javascript that starts with a $:

    echo '<script type=\"text/javascript\">$im_id='.mysql_insert_id().'</script>';

    or, don't use a $ in your variable name:

    echo "<script type=\"text/javascript\">im_id=".mysql_insert_id()."</script>";
    解决 无用
    打赏 举报

相关推荐 更多相似问题