好的,这是一个完整的示例,它当然不会访问 mySql 数据库,但它会创建一个包含来自数组的动态数据的表单。
它还会判断是否有一个url参数叫做hide,例如index.php?hide=1,这个参数会导致表单被隐藏并显示一个按钮,这个按钮会被javascript触发来显示表单。
此外,一旦发布,它将从表单中读取值。
希望这能让事情变得直截了当,没有任何疑问。
<!doctype html>
<html>
<head>
<title>Testing!</title>
</head>
<body>
<h2> This is a test </h2>
<hr/>
<?php
//this function creates the form
function createForm(){
if(isset($_GET["hide"])){ //checks if a url parameter called hide exists
//if the parameter exists, lets hide the form
$isHidden = "style='display:none;'";
//and create a button to display the form
echo "<input type='button' id='btnShowForm' value='Show Form' />";
}else{
$isHidden = "";
}
$data = ["hello", "world"]; //simulated data
$i = 0;
$dataLength = count($data)-1;
//this is the form
echo "<form id='frmTest' name='frmTest' method='POST' action='index.php' ".$isHidden.">";
while ($i <= $dataLength){
echo "<p>";
echo "<input type='radio' name='RB' value='".$data[$i]."'/>";
echo "<label>".$data[$i]."</label>";
echo "</p>";
$i++;
}
echo "<input type='submit' value='Submit Form' />";
echo "</form>";
}
//this function reads the data from the form on POST
function readFormData(){
if(isset($_POST["RB"])){ //if the page is requested as a POST
$radioValue = $_POST["RB"]; //read the RB value inside the POST data
if(isset($radioValue)) //if there's data on the variable let's display it
echo "selected value: ".$radioValue;
else
echo ":(";
}
}
if($_SERVER['REQUEST_METHOD']=='POST'){ //check if it's a post
readFormData(); //read the data
}else{
createForm(); //create the form
}
?>
</body>
<script>
var btn; //holder for the button (if exists)
window.onload = function(){ //when the page is fully loaded, jquery's $(window).load
btn = document.getElementById("btnShowForm"); //store the button, jquery's $("#btnShowForm")
if(!btn){ return; } //if no button exists, abort, jquery's if(!btn.size())
if( btn.addEventListener ){ //Every browser (except IE < 9)
btn.addEventListener("click", showForm, false); //add a click event to the button, function showForm will be fired on click, jquery's btn.click(showForm);
}else{ //IE 6,7,8
btn.attachEvent("onclick", showForm);
}
}
function showForm(){ //function to display the form
var form = document.getElementById("frmTest"); //holder for the form jquery's $("#frmTest")
form.style.display=""; //let's show the form jquery's form.show();
btn.style.display = "none"; //let's hide the button jquery's btn.hide();
}
</script>
</html>
如您所见,PHP 与 JS 完全分离,这就是它的本意。
服务器端与客户端无关,但您可以(并且应该)留下痕迹让 JS 对服务器发送的数据做一些事情。
让我们总结一下:
PHP - 创建一个表单并根据 url 参数是否隐藏它,如果它被隐藏,那么它将显示一个按钮
JS - 将寻找一个按钮,如果它存在则添加一个事件,否则,什么都不做。
是不是很轻松。。