【问题标题】:Is it possible to put a part of PHP code in <script>?是否可以将部分 PHP 代码放在 <script> 中?
【发布时间】:2015-10-06 09:00:16
【问题描述】:

我有一个 php 页面,里面是这样的警报:

<script>
alert('Stop the timer!');
</script>";

现在我想尝试/这样做:

<script>
<?php echo "$test2"; ?>
alert('Stop the timer!');
</script>

(我试图做的是通过警报返回 $test2 的内容......)

现在这不起作用。但是....它也没有给出错误信息。

所以这里有两个问题:

1) 是否可以将部分 php 放入该部分 2)如果它不起作用,为什么它不给出错误消息 (3) 我必须使 $test2 全局化吗? (以及如何最好地格式化它)

提前致谢。

 <!DOCTYPE html>
        <head>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
      <script src="//code.jquery.com/jquery-1.10.2.js"></script>
      <!-- deze hieronder is nodig voor touchpad enabled sliders -->
      <script src="jquery.ui.touch-punch.min.js"></script>
      <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
      <link rel="stylesheet" href="/resources/demos/style.css">




        <script>
    function getSelectValues(select) {
      var result = [];
      var options = select && select.options;
      var opt;

      for (var i=0, iLen=options.length; i<iLen; i++) {
        opt = options[i];

        if (opt.selected) {
          result.push(opt.value || opt.text);
        }
      }
      return result;
    }
        </script>

      <!-- accordion -->
      <script>
      $(function() {
        $( "#accordion" ).accordion({ 
            event: "click",
            active: false,
            collapsible: true,
            autoHeight: false

        });
      });
      </script>

      <script>
      $(function() {
        $( "#slider-vertical" ).slider({
          orientation: "horizontal",
          range: "min",
          min: 0,
          max: 100,
          value: 1,
          slide: function( event, ui ) {
            $( "#amount" ).val( ui.value );
          }
        });
        $( "#amount" ).val( $( "#slider-vertical" ).slider( "value" ) );
      });
      </script>
       <script>
      $(function() {
        $( "#slider-vertical2" ).slider({
          orientation: "horizontal",
          range: "min",
          min: 0,
          max: 100,
          value: 1,
          slide: function( event, ui ) {
            $( "#amount2" ).val( ui.value );
          }
        });
        $( "#amount2" ).val( $( "#slider-vertical2" ).slider( "value" ) );
      });
      </script>
        <title>Left X Right -BrainGame</title>
        <!-- Bootstrap -->
        <link href="css/bootstrap.css" rel="stylesheet">
            <script src="js/bootstrap.min.js"></script>

            <script>
      $(function() {
        $( "#datepicker" ).datepicker();
      });
      </script>
       <script>
      $(".js-example-basic-multiple").select2(); </script>

     <style type="text/css">
    p.label_checkbox_pair {
    clear: both;
    float: none;
    position: relative;
    }
    p.label_checkbox_pair input {
    left: 80px;
    position: absolute;
    top: 1px;
    }
    p.label_checkbox_pair label {
    display: block;
    margin-left: 90px;
    width: 200px;
    }
    </style>

    <script src="js/icheck.js"></script>
    <script>
    //oud $(document).ready(function(){
      //$('input').iCheck({
        //checkboxClass: 'icheckbox_polaris',
        //radioClass: 'iradio_polaris',
     // 


        //increaseArea: '20%'  optional
      //});
    //});
    $(document).ready(function(){
      $('input').each(function(){
        var self = $(this),
          label = self.next(),
          label_text = label.text();

        label.remove();
        self.iCheck({
          checkboxClass: 'icheckbox_line-blue',
          radioClass: 'iradio_line-blue',
          insert: '<div class="icheck_line-icon"></div>' + label_text
        });
      });
    });
    </script>
        <link href="skins/line/blue.css" rel="stylesheet">


        </head>

    <BODY>
    <br /><br />
    <table HSPACE="50" CELLPADDING="20">
    <tr HSPACE=50 CELLPADDING="30">
    <td>
    <?php 
    $a=array("red","blue","black","orange","green");
    $random_keys=array_rand($a,5);


    $textcolours=array('red','blue','black','orange','green');
    shuffle($textcolours);

    echo "<right><font size=6 color='$textcolours[0]' >".$a[$random_keys[0]]."<br><br></font></right>";
    echo "<right><font size=6 color='$textcolours[1]' >".$a[$random_keys[1]]."<br><br></font></right>";
    echo "<right><font size=6 color='$textcolours[2]' >".$a[$random_keys[2]]."<br><br></font></right>";
    echo "<right><font size=6 color='$textcolours[3]' >".$a[$random_keys[3]]."<br><br></font></rightr>";
    echo "<right><font size=6 color='$textcolours[4]' >".$a[$random_keys[4]]."<br><br></font></right>";
    ?>
    </td>

    <td>

      <div class="left">

         <form class="span4" action="" method="post">

      <fieldset>

        <legend>Left X Right  BrainGame</legend>

        <p halign="right" margin="10px">Name: <input type="text" name="naam" ></p>

        <p halign="right" margin="10px">Date: <input type="text" name="date" id="datepicker" ></p>

     <br>

             <?php
    if(isset($_POST['getdata'])){
    $conn=mysql_connect('localhost','t','w');
    mysql_select_db("test",$conn);

    $regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";

    $naam=$_POST['naam'];
    $date=$_POST['date'];
    //$type=$_POST['type'];
    //$core=$_POST['core'];
    //$management=$_POST['management'];


    //$names = $tools; 
    //$output = preg_grep('/(Andrew|John)/i', $names); 
    //print_r( $output );

    //
    //http://webcheatsheet.com/php/regular_expressions.php#match
    $test = $_POST['tools'];
    $result = preg_replace('/({|:|true|}|")/', '', $test);
    $test2 = preg_grep('/(^RED|^BLACK|^BLUE|^ORANGE|^GREEN|^red|^black|^blue|^orange|^green)/i', $result);

    $tools = json_encode($test2);
    //$tools = $_POST['tools'];
    //$tools = json_encode(preg_grep('/(RED|BLACK|BLUE|ORANGE|GREEN)/i', $_POST['tools']));
    //$tools = json_encode($_POST['tools']);
    //$analytisch=$_POST['analytisch'];
    //$eneagram=$_POST['eneagram'];

    if(true == false ){
        echo "<label class='err'>All fields are required</label>";
        }

            else{
    $insert="Insert into kandidaat(naam,date,tools)
     values('".$naam."','".$date."','".$tools."')";

    $rs=mysql_query($insert) or die(mysql_error());

    ?>
    <script>
    <?php echo "$test2"; ?>
    alert('Stop the timer!');

    </script>";
    <?php }
    }
     ?>

      </fieldset>


    <div id="accordion" style="width:90%;">
      <h3>Start...</h3>
      <div>
        <p class="label_checkbox_pair">

    <!--<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="iCheck" value="true"><label for="certs">ISTQB2</label></div>-->
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[RED]" value="true"><label>RED</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLUE]" value="true"><label>BLUE</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLACK]" value="true"><label>BLACK</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[ORANGE]" value="true"><label>ORANGE</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[GREEN]" value="true"><label>GREEN</label></div>
        </p>
      </div>

      <h3>Part 2</h3>
      <div>
        <p>
        <!-- zie content website https://select2.github.io/examples.html -->
        <fieldset>
    <div><input type="checkbox" name="tools[RED]" value="true"><label>RED</label></div>
    <div><input type="checkbox" name="tools[BLUE]" value="true"><label>BLUE</label></div>
    <div><input type="checkbox" name="tools[BLACK]" value="true"><label>BLACK</label></div>
    <div><input type="checkbox" name="tools[ORANGE]" value="true"><label>ORANGE</label></div>
    <div><input type="checkbox" name="tools[GREEN]" value="true"><label>GREEN</label></div>
    </fieldset>
    </p>
        </div>

    </div>


    <br/>    <button type="submit" name="getdata" class="btn">Submit</button>
    <a href="toonkandidaat.php" class="btn btn-primary">Highscores</a>


    </form>

       </div>
       <?php 
       function save(){

        }
       ?>
    <?php
    function make_links_clickable($text){
        return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Z&#1072;-&#1103;&#1040;-&#1071;()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text);
    }
    ?>

    </td>
    </tr>
    </table>

        </body>
        </html>

【问题讨论】:

  • 你自己去试试吧?
  • 就像我说的。我没有看到任何事情发生......而且我想从事实中知道它是否可以工作,然后再尝试查看不可能存在的东西:)
  • 它应该可以工作。如果您在客户端的脚本部分中没有找到$test2 的值,则意味着$test2 的值是空的。无论如何,这不会提醒$test2 的值,因为您只是在脚本部分打印它而不用它做任何事情。

标签: php


【解决方案1】:

您的语法错误。想象一下,您已将 foobar 保存在变量中。 如果你像你一样打印它,结果将是 富吧

但是您将它打印在脚本部分中,因此您需要将其分配给 JavaScript 变量。有两种方法可以提醒它。

alert("<?php echo $test; ?>");

或者

var content = "<?php echo $test; ?>";
alert(content);

【讨论】:

  • 它返回了 Array.. 所以我尝试了 .. alert("");它返回与 html 表中相同的结果...即 []
【解决方案2】:

试试这个?

<script>
alert('<?php echo $test2; ?>');
</script>

alert('<?php echo $test2; ?>');

将替换为您的 PHP 变量的内容(例如“Hello word”),就像您写的那样:

alert('Hello word');

【讨论】:

  • 嘿西蒙,本杰尼德兰德?我是 PHP 新手,很抱歉我的很多错误。警报现在是……:顺便说一句,我为您添加了代码。顺便说一句……它正在变成一个小脑游戏。 als je het leuk vind om te helpen zou ik dat wel gaaf vinden mischien.... dan kan ik je laten zien wat ik tot nu toe heb.
  • Re,哈哈,不,我不会说荷兰语 :) 我来自比利时,法国人,但像很多比利时人一样,我有一个荷兰名字... :) 也许你的内容php变量不是字符串而是数组?
【解决方案3】:

是的,这是可能的,因为 PHP 脚本首先由服务器上的 PHP 解释器评估,然后再将纯 HTML/CSS/JS 传递给客户端浏览器。

无论如何,自己尝试一下会更快。

为了回答为什么它在您的情况下不起作用,我们需要更多代码来查看您的变量的定义方式和位置。

【讨论】:

  • 这样的事情可能吗? $tools = json_encode(preg_grep('/(RED|BLACK|BLUE|ORANGE|GREEN)/i', $_POST['tools'])); ___如果是,如何正确格式化?
猜你喜欢
  • 2012-06-21
  • 2015-03-05
  • 2011-08-14
  • 2013-04-22
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2022-10-25
相关资源
最近更新 更多