有单选按钮来触发不同的 PHP 函数.. 不过目前,当点击提交按钮时页面会闪烁!
.PHP 似乎需要调整!!
希望在没有页面刷新的情况下执行功能,因此 AJAX ..
单击提交按钮(返回)时,表单字段应向 PHP 提交一个字符串,具体取决于所选的单选按钮。
网页:
<div class="container">
<!-- Input Section -->
<form action="">
<fieldset>
<legend>A Form to input plain English and output Pig Latin</legend>
<label></label>
<input class="span9" type="text" id="txt1" name="yourText" placeholder="… Type Something Here …"><br><br>
<span class="help-block">Choose whether or not you want to have the English input echoed on the output as Pig Latin:</span>
<label class="radio inline">
<input type="radio" name="optionsRadios" id="english" value="english" checked>
Echo the English Input
</label>
<label class="radio inline">
<input type="radio" name="optionsRadios" id="piglatin" value="piglatin">
Output as Pig Latin
</label>
<br><br>
<button type="submit" class="btn" onClick="showTxt(this.value)">Return</button>
</fieldset>
</form>
<br><br><br>
<!-- Output Section -->
<span id="return-text">
<p>Text Will Post Here</p>
</span>
</div>
PHP页面:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pig Latin PHP</title>
</head>
<body>
<?php
if( isset($_POST['yourText'])){
$text = $_POST['yourText'];
}
function engish(){
if( isset($_POST['optionsRadios']) &&
$_POST['optionsRadios'] == 'english'){
echo $text;
}
}
function piglatin(){
if( isset($_POST['optionsRadios']) &&
$_POST['optionsRadios'] == 'piglatin'){
echo '…pig latin php operation to be written…';
}
}
echo english();
echo piglatin();
?>
</body>
</html>
AJAX 脚本(感谢 ogc-nick 的回答):
<!-- AJAX Call to piglatin.php -->
<script>
function showTxt(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("return-text").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("return-text").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","piglatinajax.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var dataString = $('form').serialize();
xmlhttp.send(dataString);
}
感谢寻找