通过已由AJAX更新的AJAX发送值

时间:2017-03-10 09:22:34

标签: javascript ajax

我有一个表单,它从用户那里获取许多值,对它们执行计算并输出结果。每个用户编辑的字段都有一个onchange,用于触发一个函数,该函数通过AJAX调用执行计算的脚本。到目前为止一切顺利,这可以按预期工作。

但是,隐藏字段中的修饰符也会通过AJAX进行更新,具体取决于其中一个字段的用户输入。我可以看到这也有效,价值正在更新。

我的问题是,在更新此隐藏字段后,其中的新值不会发送到执行计算的脚本。我认为这是因为DOM已经通过javascript更改并需要刷新,但我无法解决如何执行此操作。

此函数调用执行返回数组的计算的脚本。

function calcPremium()
{
    var offer = 0;
    var override = 0;

    var pio = $('#policyIntroductoryOffer').prop('checked');
    var po = $('#policyOverride').prop('checked');
    if(pio)
        {
            alert('Offer checked');
            offer = 1;
        }
    if(po)
        {
            alert('Override checked');
            override = 1;
        }

    $.ajax({
        url: "calcPremium.php",
        method: "get",
        cache: false,
        data: {
                startDate : $('#policyStartDate').val(), 
                endDate : $('#policyEndDate').val(), 
                premium : $('#policyPremium').val(), 
                premium12 : $('#policy12m').val(), 
                buildingSum : $('#policyBuildingSum').val(), 
                rentSum : $('#policyRentSum').val(), 
                <?php if((isset($_GET['cat']) and $_GET['cat'] == 2) or $propertyCat == 2)
                    { ?>
                        typeRate : 100, 
                        typeRentRate : 0, 
                        typePOLRate : 0, 
                    <?php }
                else
                    { ?>
                        typeRate : $('#typeRate').val(), 
                        typeRentRate : $('#typeRentRate').val(), 
                        typePOLRate : $('#typePOLRate').val(), 
                    <?php } ?>
                rentSum1Yr : $('#policyRentSum1Yr').val(), 
                terrorZoneRate : $('#terrorRate').val(), 
                terrorZoneRentRate : $('#terrorRentRate').val(), 
                introductoryOffer : offer, 
                policyOverride : override, 
                policyIPTRate : <?php echo $iptRates['rateRate']; ?>
        },
        dataType: "json",
        success: function(policyDetails){
            console.info(policyDetails);

            $('#policyPremium').val(policyDetails[0]);
            $('#policy12m').val(policyDetails[1]);
            $('#policyDays').val(policyDetails[4]);
        },
        error: function(exception){
            alert('Exeption:'+exception);
        }
    })
}

这些功能根据用户输入更新隐藏字段

function calcRent() {
    var r1 = document.getElementById('policyRentSum1Yr').value;
    var r3 = r1 * 3;
    <?php if((isset($_GET['cat']) and $_GET['cat'] == 2) or $propertyCat == 2)
        { ?>
            rentVal = document.getElementById('policyRentSum1Yr').value;
            if(rentVal > 0)
                {
                    setZoneRate(4);
                }
            else
                {
                    setZoneRate(5);
                }
            checkDays(document.getElementById('policyStartDate').value, document.getElementById('policyEndDate').value);
            document.getElementById('terrorRate').onshow;
            document.getElementById('policyDetails').onshow;
        <?php } ?>
    document.getElementById('policyRentSum1Yr').value = r1;
    document.getElementById('policyRentSum').value = r3;
    calcPremium();
}

function setZoneRate(z) {
    if (z == "") {
        document.getElementById('terrorRate').value = "";
        document.getElementById('terrorRentRate').value = "";
        return;
    } else {
        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('terrorRates').innerHTML = xmlhttp.responseText;
                document.getElementById('terrorRates').onshow;
            }
        }
        xmlhttp.open("GET","setTerrorRates.php?q="+z,true);
        xmlhttp.send();
    }
}

以下是表单

的简化版本
    <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" name="policyAddForm" id="policyAddForm">
    <input type="hidden" name="action" value="add" />
    <h4 class="small-title">Member Details</h4>
    <input type="hidden" name="policyClient" value="<?php echo $_GET['mid']; ?>" />
    <input type="hidden" name="memberProperty" value="<?php echo $clientPropertyID; ?>" />
    <input name="clientName" type="text" class="form-control" value="<?php echo $clientName; ?>" readonly>
    <select name="clientProperty" id="clientProperty" size="1" class="form-control selectpicker" onChange="chooseProperty(this.options[selectedIndex].value);">
        <option value="">Select&hellip;</option>
        <option value="0">New property</option>
        <?php while($clientProps = $clientProps_stmt->fetch())
            {?>
                <option value="<?php echo $propertyID; ?>" <?php if($propertyType == NULL or $propertyTerrorismZone == NULL){?>data-content='<span class="text-danger" title="Incomplete property details, please edit"><i class="fa fa-exclamation-triangle"></i></span> <?php echo $propertyAddress1.', '.$propertyPostcode; if($propertyID == $clientPropertyID){ echo " [Contact address]"; }  if($propertyCat == 2){ echo " [Land]"; }?>'<?php } ?>><?php echo $propertyAddress1.', '.$propertyPostcode; if($propertyID == $clientPropertyID){ echo " [Contact address]"; }  if($propertyCat == 2){ echo " [Land]"; }?></option>
            <?php } ?>
    </select>
    <div id="clientPropertyTable">
        <span id="typeRates">
            <input type="hidden" name="typeRate" id="typeRate" value="" />
            <input type="hidden" name="typeRentRate" id="typeRentRate" value="" />
            <input type="hidden" name="typePOLRate" id="typePOLRate" value="" />
        </span>
        <span id="terrorRates">
            <input type="hidden" name="terrorRate" id="terrorRate" value="" />
            <input type="hidden" name="terrorRentRate" id="terrorRentRate" value="" />
        </span>
        <input name="propertyAddress1" id="propertyAddress1" type="text" class="form-control" value="">
        <input type="hidden" name="propertyID" id="propertyID" value="">
        <input type="hidden" name="propertyCat" id="propertyCat" value="<?php if(isset($_GET['cat']) and $_GET['cat'] == 2) {echo "2"; } else { echo "1";} ?>" />
        <input name="propertyAddress2" id="propertyAddress2" type="text" class="form-control" value="">
        <input name="propertyTown" id="propertyTown" type="text" class="form-control" value="">
        <input name="propertyCounty" id="propertyCounty" type="text" class="form-control" value="">
        <input name="propertyPostcode" id="propertyPostcode" type="text" class="form-control" value="">
        <input name="propertySqFt" id="propertySqFt" type="text" class="form-control" value="">
        <input type="hidden" name="constructionType" value="0" />
        <input type="hidden" name="propertyType" value="8" />
        <input type="hidden" name="terrorZone" value="" />
        <input type="hidden" name="propertyYear" value="0" />
        <input type="hidden" name="propertyStoreys" value="0" />
    </div>
    <div class="the-box" id="policyDetails">
    <h4 class="small-title">Policy Details</h4>
    <input name="policyReference" type="text" class="form-control" value="" required>
    <input id="policyStartDate" name="policyStartDate" type="text" class="form-control" value="" onChange="calcPremium()" required>
    <?php $yr=date('Y');
    $dn = sanitiseDate(date('d/m/Y')); // Date now
    $rd = sanitiseDate(RENEW_DATE.$yr);  // Renewal date
    if( $dn[1]  <= $rd[1])
        {
            $theDate = RENEW_DATE.$yr;
        }
    else
        {
            $yr++;
            $theDate = RENEW_DATE.$yr;
        } ?>
    <input id="policyEndDate" name="policyEndDate" type="text" class="form-control" value="<?php echo $theDate; ?>" onChange="checkDays(this.value, document.getElementById('policyStartDate').value)">
    <input id="policyDays" name="policyDays" type="text" class="form-control" value="" onChange="checkDays(document.getElementById('policyStartDate').value, document.getElementById('policyEndDate').value)">
    <input name="policyIntroductoryOffer" id="policyIntroductoryOffer" type="checkbox" value="1" onChange="calcPremium();"> Introductory Offer
    <input name="policyBuildingSum" id="policyBuildingSum" type="text" class="form-control" value="<?php if((isset($_GET['cat']) and $_GET['cat'] == 2) or $propertyCat == 2) {echo "250";} ?>" onChange="calcPremium();">
    <input name="policyRentSum1Yr" id="policyRentSum1Yr" type="text" class="form-control" value="" onChange="calcRent();">
    <input name="policyRentSum" id="policyRentSum" type="text" class="form-control" value="" onChange="calcPremium();" readonly>
    <input name="policyOverride" id="policyOverride" type="checkbox" value="1" onChange="calcPremium();"> QBE Override
    <input name="policyPremium" id="policyPremium" type="text" class="form-control" value="">
    <input name="policy12m" id="policy12m" type="text" class="form-control" value="">
    <select name="policyStatus" class="form-control" size="1">
        <?php while($theStatus = $statusResult->fetch_assoc())
            {?>
                <option value="<?php echo $theStatus['policyStatusID']; ?>"><?php echo $theStatus['policyStatusName']; ?></option>
            <?php } ?>
    </select>
</div>
    <button type="submit" class="btn btn-success btn-ha">
        <i class="fa fa-save"></i> Save changes
    </button>
</form>

1 个答案:

答案 0 :(得分:0)

您的代码中的主要问题是您对setTerrorRates.php的调用是异步的,因此它会在执行后立即返回。这样执行可能会继续执行calcRent()中的以下说明,这意味着它会在另一个调用完成其工作之前调用calcPremium()

通过将setTerrorRates的调用声明为同步来解决此问题的最简单方法

xmlhttp.open("GET", "setTerrorRates.php?q=" + z, false);

最后,由于您使用的是jQuery,请考虑在calcRent()setZoneRate()函数中利用其功能。

修改

您还可以删除以编程方式更改的表单的onChange属性。当输入失去焦点时触发该事件,而不是通过代码更改其值时触发。

我还建议将html代码中的所有其他onChange值移到脚本中。虽然不是强制性的,但将表达和功能分开通常是一种很好的做法。