0

我正在执行一项任务,我将创建一个抵押计算器,该计算器使用 Javascript/Ajax 采用“融资金额”和“利率”来计算每月付款。“金额”和“利息”由用户填写,每月付款在 PHP 程序中计算并发送回“付款”字段。

我需要验证用户输入并获取“付款”字段以显示计算的付款。

现在我如何编码它在我按下提交时验证正确,但计算出的付款值显示在一个单独的页面上(除了打印行之外,php 页面是空白的)。

这是我的 HTML 页面代码:

<link rel="stylesheet" type="text/css" href="css/king.css" />

    <script>
    var XMLHttpRequestObject = false;

        if (window.XMLHttpRequest) {
          XMLHttpRequestObject = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
          XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        }

        function calculateRate()
        {

          if(XMLHttpRequestObject) {

            XMLHttpRequestObject.open("POST", "assignment_8_calculate.php");

            XMLHttpRequestObject.setRequestHeader('Content-Type',
              'application/x-www-form-urlencoded');

            XMLHttpRequestObject.onreadystatechange = function()
            {
              if (XMLHttpRequestObject.readyState == 4 &&
                XMLHttpRequestObject.status == 200) {

                  var returnedData = XMLHttpRequestObject.responseText;

                  var payment = document.getElementById('payment');
                  payment.value = returnedData;
              }
            }

            var amount = document.getElementById('amount').value;
            var interest = document.getElementById('interest').value;

            XMLHttpRequestObject.send(amount);
            XMLHttpRequestObject.send(interest);

          }

          return false;

        }


    function validateForm()
    {
        var errmsg = '';

        var amount = document.getElementById('amount').value;

        if (amount == null || amount == "")
        {
          errmsg += "<br />You must enter an 'Amount Financed'";
        } else {

            if (isNaN(amount))
            {
                errmsg += "<br />'Amount Financed' must be a number";
            }

        }

        var interest = document.getElementById('interest').value;

        if (interest == null || interest == "")
        {
          errmsg += "<br />You must enter an 'Interest Rate'";

        } else {

            if (isNaN(interest))
            {
                errmsg += "<br />'Interest Rate' must be a number";
            }

        }

        var messageDiv = document.getElementById('messagediv');

        messageDiv.innerHTML = errmsg;

        if (errmsg == '')
        {
            return true;
        } else {
            return false;
        }

    }

    </script>

</head>

<body>
<body>
<a href="assignment_8.php"><img src="images/KingLogo.jpg"></a><br>

<div id="mortgagecalculatorresults">
<h2>Mortgage Calculation</h2>

<div id="calculator">

    <form id="mortgage" method="post" action="assignment_8_calculate.php">

    <table>
    <tr>
    <td>Amount Financed:</td>
    <td><input type="text" name="amount" id="amount" ></td>
    </tr>

    <tr>
    <td>Interest Rate:</td>
    <td><input type="text" name="interest" id="interest" ></td>
    </tr>

    <tr>
    <td>Calculated Monthly Payment:</td>
    <td><input type="text" disabled="disabled" name="payment" id="payment" ></td>
    </tr>
    </table>

    <p><input type="submit" value="Calculate Payment" onclick="return validateForm()" onsubmit=" calculateRate();">

    <input type="reset" />
    </p>

    </form>

</div>

<div style="color: red;" id="messagediv">
</div>


</body>
</html>

我还尝试将值一次发送到 PHP 程序,如下所示:

var sendValues = amount + '|' + interest;
XMLHttpRequestObject.send(sendValues);

这是 PHP 页面的代码(请注意,在代码中,我尝试仅发送一个值并在我的 php 中分解它的示例被注释掉了):

<?php
//$sendValues = $_POST['sendValues'];
$amount = $_POST['amount'];
$interest = $_POST['interest'];

//list($amount, $interest) = explode('|', $sendValues);

$payment = ($amount * $interest) / 12;
//$payment = $sendValues / 12;
$payment = number_format ($payment, 2);

print $payment;

?>

如果我将按钮编码为按钮而不是提交,直接连接到 claculateRate 函数并跳过验证,则将无用的值返回到隐藏字段而不发送到单独的 PHP 页面,但发送的值将始终为 0.00 .

谢谢!!!

更新的代码:不工作 - 出现错误:

“方法不允许

URL /testfiles/Ungar_Bradley_1585_PHPwithMySQL/assignment_8_mortgage.html 不允许请求的方法 POST。”

如果我只是将“按钮”类型更改为“提交”,那么我会在要返回该值的“付款”字段中获得 0.00 值。

<html>
<head>

    <link rel="stylesheet" type="text/css" href="css/king.css" />

        <script>
        var XMLHttpRequestObject = false;

            if (window.XMLHttpRequest) {
              XMLHttpRequestObject = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
              XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
            }

            function calculateRate()
            {

              if(XMLHttpRequestObject) {

                XMLHttpRequestObject.open("POST", "assignment_8_calculate.php");

                XMLHttpRequestObject.setRequestHeader('Content-Type',
                  'application/x-www-form-urlencoded');

                XMLHttpRequestObject.onreadystatechange = function()
                {
                  if (XMLHttpRequestObject.readyState == 4 &&
                    XMLHttpRequestObject.status == 200) {

                      var returnedData = XMLHttpRequestObject.responseText;

                      var payment = document.getElementById('payment');
                      payment.value = returnedData;
                  }
                }

                var amount = document.getElementById('amount').value;
                var interest = document.getElementById('interest').value;

                XMLHttpRequestObject.send(amount);
                XMLHttpRequestObject.send(interest);

              }

              return false;

            }


        function validateForm()
        {
            var errmsg = '';

            var amount = document.getElementById('amount').value;

            if (amount == null || amount == "")
            {
              errmsg += "<br />You must enter an 'Amount Financed'";
            } else {

                if (isNaN(amount))
                {
                    errmsg += "<br />'Amount Financed' must be a number";
                }

            }

            var interest = document.getElementById('interest').value;

            if (interest == null || interest == "")
            {
              errmsg += "<br />You must enter an 'Interest Rate'";

            } else {

                if (isNaN(interest))
                {
                    errmsg += "<br />'Interest Rate' must be a number";
                }

            }

            var messageDiv = document.getElementById('messagediv');

            messageDiv.innerHTML = errmsg;

            if (errmsg == '')
            {
                calculateRate();
                return true;
            } else {
                return false;
            }

        }

        </script>

</head>

<body>
<body>
<a href="assignment_8.php"><img src="images/KingLogo.jpg"></a><br>

<div id="mortgagecalculatorresults">
<h2>Mortgage Calculation</h2>

<div id="calculator">

    <form id="mortgage" method="post">

    <table>
    <tr>
    <td>Amount Financed:</td>
    <td><input type="text" name="amount" id="amount" ></td>
    </tr>

    <tr>
    <td>Interest Rate:</td>
    <td><input type="text" name="interest" id="interest" ></td>
    </tr>

    <tr>
    <td>Calculated Monthly Payment:</td>
    <td><input type="text" disabled="disabled" name="payment" id="payment" ></td>
    </tr>
    </table>

    <p><input type="submit" value="Calculate Payment" onclick="return validateForm()" onsubmit="return false;">

    <input type="reset" />
    </p>

    </form>

</div>

<div style="color: red;" id="messagediv">
</div>


</body>
</html>
4

2 回答 2

1

有几件事我会改变,但我想这取决于你的老师会允许什么

我会在整个项目中使用 jquery。

http://docs.jquery.com/Plugins/Validation将能够处理您需要的任何验证

下面的代码可以更好地从 php 脚本中收集信息

$.ajax({
    data: {'amount':amount,'interest':interest},
    type: "POST",
    url: "assignment_8_calculate.php",
    success: function (data) {
        if (data) {
            alert(data);
        } else {
            alert('data not found');
        }
    }
});
于 2012-09-12T21:13:49.650 回答
1

action="assignment_8_calculate.php"表单元素中删除,onsubmit=" calculateRate();"从提交按钮中删除,添加onsubmit="return false;"表单元素,最后,在validateForm()如果没有错误后返回true的函数中,将其更改为

if (errmsg == '')
{
    calculateRate();
}
return false;
于 2012-09-12T21:15:39.210 回答