我有以下代码
<html>
<head>
<title>Javascript function </title>
<style type="text/css">
.box
{
width:400px;
background-color:#F0F8FF;
}
h4
{
color:#09F
}
</style>
<script type="text/javascript">
function hello(){
var xx=eval(form1.text1.value);
var yy=eval(form1.text2.value);
form1.text3.value=xx+yy
}
</script>
</head>
<body onLoad="form1.text1.focus()">
<center>
<div class="box">
<h1 style="color:#2c80d3 ">Javascript Function</h1>
<table border="0" cellspacing="1" cellpadding="1" width="25%">
<form name="form1" action="textboxes.php" method="Post">
<tr><td> First</d><td width="20px"><input type="text" name="text1" value=""></td></tr>
<tr><td> Second</d><td><input type="text" name="text2" value="" onBlur="hello()"></td></tr>
<tr><td> Result</d><td><input type="text" name="text3" value="" disabled=""></td></tr>
</form>
</table>
<h4>Enter any digit in text1 and text2 and see result in text3</h4>
<h4>Is it possible to do above with php without submitting FORM?</h4>
</div>
</center>
</body>
</html>
没问题,它很好用。我使用java脚本对两个数字求和。是否可以在不使用任何提交按钮的情况下使用php添加两个数字?
如果是,请引导我。
http://i41.tinypic.com/2rfev7m.jpg
如果你想在没有提交按钮的情况下使用php,你可以使用javascript向服务器发出AJAX请求,服务器会计算出值,然后将其返回给客户端。
这是工作示例。
首先,我们需要创建一个名为add.html的html文件。这是add.html文件的代码…
<!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>Addition</title>
</head>
<body>
<form action="result.php" method="post">
Enter first Integer: <input type="text" name="first" size="5" /><br/>
Enter second Integer: <input type="text" name="sec" size="5" /><br/>
<input type="submit" name="submit" value="Add" />
</form>
</body>
</html>
将其放在pseudo-server文件夹中。如果您的伪服务器是WampServer,那么文件的路径将是
C:/wamp/www/add.html
现在打开你最喜欢的浏览器,进入地址栏键入
localhost/add.html
您可以看到add.html页面。添加编号
您可以看到两个可以输入数字的文本框和一个提交按钮。您可以在输入框中输入两个数字,然后按下提交按钮(添加按钮)。但什么都不会发生。因为php将完成添加工作。
让我们创建php文件。你可以把它命名为result.php。正如我已经在add.html表单中声明的那样,action就是result.php。
<form action="result.php" method="post">
如果您给出了不同的php文件名称,那么请在add.html中更改表单action php名称。以下是result.php…的php代码
<?php //Starting of php
$first = $_POST['first']; //Getting Value of first integer from add.html
$sec = $_POST['sec']; //Getting Value of Second integer from add.html
$res = $first + $sec; //Adding the two values and placing the added result to 'res' variable
echo 'Added Result:';
echo $first." + ".$sec." = ".$res; //Showing the result to the screen
//Ending of php
?>
将这个result.php文件保存在已经放置add.html文件的服务器路径中。现在是测试的时候了。打开你最喜欢的浏览器,在地址栏中键入…
localhost/add.html
输入两个数字,然后点击"添加"按钮。您将看到浏览器将引导您进入result.php页面,在那里您可以看到添加的结果。
希望这对你有帮助。