为什么onsubmit事件处理程序在php解释器中不起作用

时间:2019-05-25 18:40:45

标签: javascript php

我正在阅读学习PHP,MySQL和Javascript第4版,在第16章中遇到了一个问题。

Onsubmit事件处理程序无法在<?php ... ?>(PHP解释器)中运行,而没有它则可以正常工作。 我错过了什么吗?

我删除了部分代码只是为了显示问题

<?php
echo <<<_END
    <!DOCTYPE html>
        <html>
            <head>
                <title>An Example Form</title>
                <style>
                    .signup {
                        border:1px solid #999999;
                        font:  normal 14px helvetica;
                        color: #444444;
                    }    
                </style>
                <script>
                    function validate(form) {
                        fail  = validateForename(form.forename.value)

                        if(fail == "")   return true
                        else { alert(fail); return false }
                    }

                    function validateForename(field) {
                        return (field == "") ? "No Forename was entered.\n" : ""
                    }
                </script>
            </head>
            <body>
                <table border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
                    <th colspan="2" align="center">Signup Form</th>
                    <form method="post" onsubmit="return validate(this)">
                        <tr><td>Forename</td>
                            <td><input type="text" maxlength="32" name="forename"></td>
                        </tr>
                        <tr><td colspan="2" align="center">
                            <input type="submit" value="Signup"></td>
                        </tr>
                    </form>
                </table>
            </body>
        </html>
_END;
?>

使用此代码后,即使我提交了一个空白表格,javascript警报功能也不会显示任何警报。

这里只是HTML / CSS / JS:

<!DOCTYPE html>
<html>

<head>
  <title>An Example Form</title>
  <style>
    .signup {
      border: 1px solid #999999;
      font: normal 14px helvetica;
      color: #444444;
    }
  </style>
  <script>
    function validate(form) {
      fail = validateForename(form.forename.value)

      if (fail == "") return true
      else {
        alert(fail);
        return false
      }
    }

    function validateForename(field) {
      return (field == "") ? "No Forename was entered.\n" : ""
    }
  </script>
</head>

<body>
  <table border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
    <th colspan="2" align="center">Signup Form</th>
    <form method="post" onsubmit="return validate(this)">
      <tr>
        <td>Forename</td>
        <td><input type="text" maxlength="32" name="forename"></td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input type="submit" value="Signup"></td>
      </tr>
    </form>
  </table>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

您必须两次对换行符\n进行转义,否则HTML输出将不符合预期:

return (field == "") ? "No Forename was entered.\\n" : ""