我怎么能写php和javascript混合

时间:2016-02-03 05:50:08

标签: javascript php

这是一个php页面

echo '<script>
            function myFunction() {

                if (confirm("Are you sure you want to delete Advertiser ID : '.$advr_id.', This advertiser has campaign also!") == true) 
                {'.
                    while ($row_camp = mysql_fetch_array($result))
                    {
                        $camp_id = $row_camp["camp_id"];
                    }

                .'}
                  else{};
            }
       </script>';

我在之前和之后得到错误。我如何连接它们?

2 个答案:

答案 0 :(得分:0)

可能处于这种模式,可能是我想念一些变量,但这是个主意 试试这个,因为我改了它

<强> PHP

 <?php
 ?>
   <script>
        function myFunction() {
            var x;
            if (confirm("Are you sure you want to delete Advertiser ID : <?php echo $advr_id; ?>, This advertiser has campaign also!") == true)  

  {
             <?php echo 'x="ok"; alert(x);';
        /* while ($row_camp = mysql_fetch_array($result))
                {
                    $camp_id = $row_camp["camp_id"]; //but may be echo something here is need?
                }*/ 
      ?>

            } else {
                x = "You pressed Cancel!"; alert(x);
            }
        }
    myFunction();
   </script>

答案 1 :(得分:0)

我不明白为什么是downvotes,这是学习PHP JS堆栈的一个常见错误。

无论如何,我认为您需要了解PHP(后端)和Javascript(前端)如何交互。

From W3School

长话短说,你的if javascript代码应该向你的后端服务器发送一个全新的请求(使用ajax或使用html的简单http请求,你知道,一个表单和一个提交按钮)并让你的while PHP代码删除数据库。

<强>更新

这是一个非常基本的例子

view.php

<script type="text/javascript">
    function myFunction() {
        var x;
        if (confirm("Are you sure you want to delete Advertiser ID : '<?php echo $advr_id; ?>.', This advertiser has campaign also!") == true) {
            window.location = '/delete.php?id=<?php echo $advr_id; ?>';
        } else {
            x = "You pressed Cancel!";
        }
    }
</script>

delete.php

<?php

$advr_id = $_GET['advr_id'];
// delete from database