外部php表单结果

时间:2011-06-05 17:00:17

标签: php html

我已经使用javascript在电子商务网站中创建了动态定价表单,并且工作正常。但是,我更希望将更复杂的定价计算放在HTML表单外部的PHP文件中。 计算是相当复杂的,我已经让他们都使用PHP工作但是我是PHP的新手,并且我的生活无法弄清楚如何将计算结果返回到html表单。然后用户可以“添加到购物车”

以下是尝试和解释

的非常简单的示例

HTML表单

<html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demoform</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="myform.php">
<label>Width<input type="text" name="width" id="width" size="6"></label><p>
<label>Length<input type="text" name="length" id="length" size="6" ></label><p>
<label>Price $</label> <input id="Price" readOnly size=6 name=Price><p>
<label for=otherprice></label><input id="otherprice" readOnly size=6  type=hidden 
name=otherprice><p>
<input type="submit" name="submit" id="submit" value="Get Price" ><p>
<input id="addtocart" title="Add to Cart" onclick="return validate(this.form)" value="Add to Cart" type="submit" ?>
</form>
</body>
</html> 

PHP文件

<?php

$width=$_POST['width'];
$length=$_POST['length'];
$Area = $width*$length;
$total = $Area * .01;
$price = round($total * 100) / 100;
$otherprice = round($price * 1.2 * 100)/100 ;

?>

<?php echo "$price"?><br/>
<?php echo "$otherprice"?>

而不是新的页面打开是可能的 要将$ price输入到HTML价格字段中 并将$ otherprice输入demoform.html页面中的HTML otherprice(隐藏)字段

约翰

1 个答案:

答案 0 :(得分:3)

PHP脚本:

<?php
$width =$_GET['width'];
$length = $_GET['length'];
$area = $width * $length;
$total = $area * .01;
$price = round($total * 100) / 100;
$otherprice = round($price * 1.2 * 100) / 100;

echo json_encode(array($price, $otherprice));
?>

<强> JavaScript的:

function Ajax() {
    this.instance = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    this.request = function(url, callback) {
        this.instance.open('GET', url, true);
        this.instance.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                callback(this.responseText);
            }
        }
        this.instance.send(null);
    }
}
function validate(form) {
    (new Ajax).request('prices.php?width=' + form.width.value + '&length=' + form.length.value, function(respons) {
        var prices = eval(respons);
        form.price.value = prices[0];
        form.otherprice.value = prices[1];
    });
}

Ajax类是我创建的。您可以自由使用它。你也可以在没有上课的情况下完成。我通常这样做,因为它很容易制作多个XHR对象。

<强> HTML:

<form name="form1" method="post" action="myform.php">
    <p>
        <label>Width <input type="text" name="width" size="6" /></label><br />
        <label>Length <input type="text" name="length" size="6" ></label><br />
        <label>Price <input type="text" name="price" readonly="readonly" size="6" /></label>
        <input type="hidden" name="otherprice" readonly="readonly" size="6" /><br />
        <input type="button" value="Get Price" onclick="validate(this.form)" />
    </p>
    <p>
        <input type="submit" value="Add to Cart" />
    </p>
</form>

另外请清理您的HTML。 :)

相关问题