1.將表單中的action屬性值設為PHP路徑,則網頁會跳轉到這個網址
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> //當然,action要與submit配合 </form>
</body>
</html>
<html> <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> //數據可以使用超全局變量讀取 </body> </html>
2.通過Ajax方法,特點在於不需要跳轉至PHP頁面
<div> <input type="text" id="user" value="sb" /> <input type="password" id="password" value="sb" /> <input type="button" id="send" /> <p id="pword"></p> </div> <script type="text/javascript"> $("#send").click(function(){ $.post("http://127.0.0.1/return.php",{ username:$("#user").val(), password:$("#password").val() }, function(data,textStatus){ $("#pword").html(data); } ); }); </script>
<?php header('Access-Control-Allow-Origin:*'); //這句作用是允許任何網址訪問 $user=$_POST['username']; $password=$_POST['password']; $text="username:$user"." "."password:$password"; echo $text; ?>
當然,除了以上方法外,還可采用PHP內嵌HTML或者HTML內嵌PHP中,不過這樣代碼可讀性較差,比較雜亂。(雖然我的代碼怎么都寫不整齊。。。 : (