dongpei3245 2018-02-06 19:00
浏览 76
已采纳

由于Ajax数据参数不正确,文本会多次追加。 什么是正确的参数?

I'm fairly new to Ajax. I am getting the correct values from the PHP url in my Ajax function. The problem is that my data parameter is causing it to duplicate values.

Here is what is displaying on the actual webpage:

error

Here is the console.log output:

[2000, 335.1032163829112]
[2000, 335.1032163829112]
[2000, 335.1032163829112]
[2000, 335.1032163829112]
[2000, 335.1032163829112]

The form has 5 input fields, so I'm assuming since the Ajax function says $('form').serialize(), it's returning the requested values as many times are there are input fields.

What is the correct data parameter to send what I need? I only need 2 values that are calculated in my php script.

Here is the initial form, then the hidden div and Ajax call:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Volume Calculator</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="container page-heading">
    <h2>Volume Calculator</h2>
</div>
<!--<form class="form-horizontal" method="post" action="result.php">-->
<form id="form" class="form-horizontal" method="post" action="">
    <div class="form-container">
        <p class="calculate-heading">Calculate Volume of a Rectangle</p>
    </div>
    <div class="container form-container">
        <div class="row">
            <div class="form-group form-group-sm col-sm-6">
                <div class="row">
                    <label for="width" class="col-sm-3 col-form-label">Width: </label>
                    <div class="col-sm-9">
                        <input type="number" class="form-control pull-left" id="width" name="width" required>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group form-group-sm col-sm-6">
                <div class="row">
                    <label for="length" class="col-sm-3 col-form-label">Length: </label>
                    <div class="col-sm-9">
                        <input type="number" class="form-control pull-left" id="length" name="length" required>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group form-group-sm col-sm-6">
                <div class="row">
                    <label for="height" class="col-sm-3 col-form-label">Height: </label>
                    <div class="col-sm-9">
                        <input type="number" class="form-control pull-left" id="height" name="height" required>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12 bs-linebreak">
            <!-- NOTHING. JUST A LINE BREAK -->
        </div>
    </div>
    <div class="form-container">
        <p class="calculate-heading">Calculate Volume of a Cone</p>
    </div>
    <div class="container form-container">
        <div class="row">
            <div class="form-group form-group-sm col-sm-6">
                <div class="row">
                    <label for="radius" class="col-sm-3 col-form-label">Radius: </label>
                    <div class="col-sm-9">
                        <input type="number" class="form-control pull-left" id="radius" name="radius" required>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group form-group-sm col-sm-6">
                <div class="row">
                    <label for="cone_height" class="col-sm-3 col-form-label">Height: </label>
                    <div class="col-sm-9">
                        <input type="number" class="form-control pull-left" id="cone_height" name="cone_height"
                               required>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container form-container">
        <div class="row">
            <!--<button type="submit" id="submit-btn" class="btn btn-primary">Calculate</button>-->
            <button type="button" id="submit-btn" class="btn btn-primary">Calculate</button>
        </div>
    </div>
</form>

Hidden div that appears and Ajax function:

<!-- NEW DIV THAT APPEARS ON FORM SUBMIT. HIDDEN BY DEFAULT VIA JQUERY -->
<div id="result-form" class="form-horizontal">
    <div class="form-container">
        <p class="calculate-heading">Summary of Calculations</p>
    </div>
    <div class="row">
        <div class="col-md-12 bs-linebreak">
            <!-- NOTHING. JUST A LINE BREAK -->
        </div>
    </div>
    <div class="form-container">
        <p class="calculate-heading calculate-heading-bold">Volume of Rectangle</p>
        <p id="length-p" class="calculate-heading">Length: </p>
        <p id="width-p" class="calculate-heading">Width: </p>
        <p id="height-p" class="calculate-heading">Height: </p>
        <br>
        <p id=rec_volume-p" class="calculate-heading">The Volume of the Rectangle is <strong></strong></p>
    </div>
    <div class="form-container">
        <p class="calculate-heading calculate-heading-bold">Volume of a Cone</p>
        <p id="radius-p" class="calculate-heading">Radius: </p>
        <p id="cone_height-p" class="calculate-heading">Height: </p>
        <br>
        <p id="cone_volume-p" class="calculate-heading">The Volume of the Cone is <strong></strong></p>
    </div>
</div>
</body>
<script>
    //HIDE THE DIV WHEN DOCUMENT IS LOADED
    $(document).ready(function() {
        $('#result-form').hide();
    });
    //GET RID OF DEFAULT HTML INVALID WARNING
    $('input').on("invalid", function (e) {
        e.preventDefault();
    });
    //HANDLE BUTTON SUBMIT
    //LOOP THROUGH ALL INPUT ELEMENTS AND CHECK FOR INVALID FIELDS
    $('#submit-btn').click(function () {
        $('form input[type!=submit]').each(function () {
            if ($(this).val() == '') {
                alert("All fields are required");
                return false;
            }
            else {

                //AJAX CALL HERE
                $.ajax({
                    type:'post',
                    url:'calculate.php',
                    data: $('form').serialize(), //<-- THIS IS THE PROBLEM, BUT I DON'T KNOW WHAT TO DO
                    success: function(output) {
                        var result = $.parseJSON(output);
                        console.log(result);
                        $('#result-form').show();
                        $('#length-p').append($('#length').val());
                        //REST OF THE VALUES UNDER THIS
                    }
                });

            }
        });
    });
</script>

The calculate.php script:

<?php
//Rectangle dims
$width = $_POST['width'];
$length = $_POST['length'];
$height = $_POST['height'];

//Cone dims
$radius = $_POST['radius'];
$cone_height = $_POST['cone_height'];

//Rectangle volume
$rec_volume = $width * $length * $height;
//Cone volume
$cone_volume = 1/3 * (M_PI * pow($radius, 2) * $cone_height);

echo json_encode(array($rec_volume, $cone_volume));

I would really like to do this asynchronously instead of going to a completely new page. It just seems redundant. What is the correct data parameter?

Thanks.

  • 写回答

1条回答 默认 最新

  • dongyou2635 2018-02-06 19:42
    关注

    Your code loops over every variable in the form and issues an ajax call. Each ajax call returns and appends the results to the #length-p element.

    The solution is to only call the ajax once, after you've verified all the elements are filled out. This should do it.

    $('#submit-btn').click(function () {
        // validate, failures issue alert and exist the call.
        $('form input[type!=submit]').each(function () {
            if ($(this).val() == '') {
                alert("All fields are required");
                return false;
            }
         });
    
         // no failure, so issue the request. 
         //AJAX CALL HERE
         $.ajax({
            type:'post',
            url:'calculate.php',
            data: $('form').serialize(), //<-- THIS IS THE PROBLEM, BUT I DON'T KNOW WHAT TO DO
            success: function(output) {
                var result = $.parseJSON(output);
                console.log(result);
                $('#result-form').show();
                $('#length-p').append($('#length').val());
                //REST OF THE VALUES UNDER THIS
            }
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条