douhuan6305 2013-07-31 13:05
浏览 42

如何将PHP变量值分配给JavaScript变量

In this code which I am posting i have one problem. I want my PHP variable to be stored in JavaScript variable but it shows error. The code is below.

<?php
    $name="anurag singh";

    echo '
        <html>
            <head>
            <script type="text/javascript" src="jquery-2.0.2.js"></script>
            <script type="text/javascript">
                $(document).ready(function(){
                    var name1=.$name.";"
                    $.post("main_page.php",{input1: name1}, function(msg){
                        alert("hi "+msg);
                    });
                });
            </script>
            </head>

            <body>
                <h1>This is the demo!</h1>
                <h2>In echo we can add more than one statements</h2>
            </body>
        </html>
    ';
?>

Now when I am assigning $name to the variable name1 than I get an syntax error. Please let me know what changes I have to make. So that I get the value of the PHP variable $name stored in JavaScript variable name1.

  • 写回答

6条回答 默认 最新

  • dongxun1244 2013-07-31 13:07
    关注

    In javascript with echo version: var name1= "'.$name.'";

    <?php
    $name = "anurag singh";
    echo '
        <html>
            <head>
            <script type="text/javascript" src="jquery-2.0.2.js"></script>
            <script type="text/javascript">
                $(document).ready(function(){
                    var name1= "'.$name.'";
                    $.post("main_page.php",{input1: name1}, function(msg){
                        alert("hi "+msg);
                    });
                });
            </script>
            </head>
    
            <body>
                <h1>This is the demo!</h1>
                <h2>In echo we can add more than one statements</h2>
            </body>
        </html>
        ';
    ?>
    

    And you can use like var name1= "<?php echo $name; ?>"; seperated html and php

    <?php
       $name="anurag singh";
    ?>
    
    <html>
        <head>
        <script type="text/javascript" src="jquery-2.0.2.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var name1= "<?php echo $name; ?>";
                $.post("main_page.php",{input1: name1}, function(msg){
                    alert("hi "+msg);
                });
            });
        </script>
        </head>
    
        <body>
            <h1>This is the demo!</h1>
            <h2>In echo we can add more than one statements</h2>
        </body>
    </html>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程