<?php
include_once("add.php");
function click(){
if($_POST['username']=="" ||$_POST['title']==""){
echo "<script language='javascript'>";
echo "alert('用户和标题不能为空!')";
echo "</script>";
}
else
echo "发表成功!";
}
?>
<form action="add.php" method="post">
用户:<input type="text" name="username" size="10" /><br/>
标题:<input type="text" name="title"/><br/>
内容:<textarea name="text" rows="5" cols="30"></textarea><p>
<input type="submit" name="submit" value="发表留言" onclick="click()" />
</form>

解决方案 »

  1.   

    js调用php中定义的函数?完全独立的两个层面啊。
      

  2.   

    HTML中调用 不是JS中调用 还有这个文件名就是add.php
      

  3.   

    基础概念问题,php是运行在服务端的,js是运行在客户端的。
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    </head><body>
    <?php
    echo "<script type=\"text/javascript\">\n";
    if ($_POST['username'] == '' || $_POST['title'] == '')  echo "alert('用户和标题不能为空!')\n";
    else echo "alert('发表成功!')\n";
    echo "</script>\n";
    ?>
    <form action="add.php" method="post">
        用户:<input type="text" name="username" size="10" /><br/>
        标题:<input type="text" name="title"/><br/>
        内容:<textarea name="text" rows="5" cols="30"></textarea><p>
        <input type="submit" name="submit" value="发表留言" />
    </form>
    </body>
    </html>
      

  4.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    </head><body><?php
    echo "<script type=\"text/javascript\">\n";
    if ($_POST['username'] == '' || $_POST['title'] == '')  echo "alert('用户和标题不能为空!')\n";
    else echo "alert('发表成功!')\n";
    echo "</script>\n";
    ?>
    <script type="text/javascript">
    function validate() {
    var username = document.getElementsByTagName('input')[0].value;
    var title = document.getElementsByTagName('input')[1].value;
    if (username.length < 1 || title.length < 1) {
    alert('用户和标题不能为空!');
    return false;
    }
    else return true;
    }
    </script>
    <form action="add.php" method="post" onsubmit="return validate();">
        用户:<input type="text" name="username" size="10" /><br/>
        标题:<input type="text" name="title"/><br/>
        内容:<textarea name="text" rows="5" cols="30"></textarea><p>
        <input type="submit" name="submit" value="发表留言" />
    </form>
    </body>
    </html>