从AJAX中的JSON中删除“未定义”值

时间:2018-01-25 15:31:19

标签: javascript jquery json ajax

我有一个表单,通过AJAX将数据作为JSON提交给GoogleSheet。

我想更改它,以便空白字段显示为空,而不是在Google表格中显示为undefined

以下是我的代码:

HTML表单:

<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
    <title>MooWoos Stall Booking</title>
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="UTF-8">

    <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    <!--build:css css/styles.min.css-->
        <link rel="stylesheet" href="/css/bootstrap.css">
        <link rel="stylesheet" href="/css/style.css">
    <!--endbuild-->

</head>

<body>
<div class="container">
    <nav class="navbar navbar-toggleable-md navbar-light">
        <a class="logo"><img src="assets/logo_opt.png" alt="MooWoos Stall Booking"></a>
    </nav>

    <hr>

    <div class="modal fade" id="redirect_page" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="form-horizontal">

                    <div class="modal-body">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <div id="user_msg">Booking successful! Redirecting to PayPal... </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6 col-md-offset-3 bookingform">
            <h1>Stall Booking Form</h1>
            <p class="lead">
                Fill out the form to book and pay for your stall!
            </p>
            <form id="bookingForm" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
                <!-- BELOW ARE PAYPAL FIELDS FROM PAYPAL GENERATION -->
                <input type="hidden" name="cmd" value="_s-xclick">
                <input type="hidden" id="hosted_button_id" name="hosted_button_id" value="js_value">
                <input type="hidden" name="currency_code" value="GBP">
                <div class="form-group">
                    <label for="name">Name </label>
                    <input type="text" id="name" name="name" class="form-control" placeholder="Your Name" value="" title="Please enter your name" required/>
                </div>
                <div class="form-group">
                    <label for="address">Address </label>
                    <textarea id="address" name="address" class="form-control" placeholder="Your Address" title="Please enter your address" required></textarea>
                </div>
                <div class="form-group">
                    <label for="phone">Telephone Number </label>
                    <input type="tel" id="phone" pattern="(([0]{1})|([\+][4]{2}))([1]|[2]|[3]|[7]){1}\d{9}$" name="phone" class="form-control" placeholder="Your Telephone Number" value="" title="Please enter the best telephone number to contact you on" required/>
                </div>
                <div class="form-group">
                    <label for="email">Email </label>
                    <input type="email" id="email" name="email" class="form-control" placeholder="Your Email" value="" title="Please enter your Email address" required/>
                </div>
                <div class="form-group">
                    Which date would you like to book?
                    <p></p>
                    <p><input type="radio" name="date" value="13th September" required/> Sunday 13th September</p>
                    <p><input type="radio" name="date" value="6th February" /> Saturday 6th February</p>
                </div>
                <div class="form-group">
                    <label>What type of stall do you require?</label>
                    <div>
                        <input type="radio" name="stallType" id="stallType-Preloved" value="Preloved" required>
                        <label for="stallType-Preloved">Preloved</label>
                        <div class="reveal-if-active form-inline">
                            Will you be bringing a clothes rail?
                            <label class="stallLabel" for="c-rail-yes">Yes</label> <input type="radio" id=c-rail-yes name="c-rail" value="Yes" />
                            <label class="stallLabel" for="c-rail-no">No</label> <input type="radio" id=c-rail-no name="c-rail" value="No" />
                        </div>
                    </div>
                    <div>
                        <input type="radio" name="stallType" id="stallType-Craft" value="Craft">
                        <label for="stallType-Craft">Craft</label>
                        <div class="reveal-if-active">
                            <label for="craftName">What name do you use?</label>
                            <input type="text" id="craftName" name="craftName" class="require-if-active form-control" placeholder="Craft Name" title="Please provide us with your Craft name" value="" />
                        </div>
                    </div>
                    <div>
                        <input type="radio" name="stallType" id="stallType-Business" value="Business">
                        <label for="stallType-Business">Business</label>
                        <div class="reveal-if-active">
                                <label for="bizName">What is your business name?</label>
                                <input type="text" id="bizName" name="bizName" class="require-if-active form-control" placeholder="Business Name" title="Please provide us with your Business name" value="" />
                                <br>
                                Do you have Public Liability Insurance?
                                <label class="insuranceLabel" for="insurance-yes">Yes</label> <input type="radio" id="insurance-yes" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="We will require proof of this prior to market day" value="Yes"/>
                                <label class="insuranceLabel" for="insurance-no">No</label> <input type="radio" id="insurance-no" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="Our insurance does not cover other businesses. Please ensure you have adequate cover and provide us with proof prior to market day" value="No"/>
                        </div>
                    </div>
                </div>
                    <div>
                        <input type="submit" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" />
                    </div>
            </form>
            <p></p>
        </div>

    </div>

    <hr>

    <footer>
        <div class="row">
            <div class="col-lg-12">
                <p>Copyright &copy; MooWoos 2018. Booking Form by Luke Brewerton</p>
            </div>
        </div>

    </footer>

</div>

<!--build:js js/mwbookings-min.js -->
<script src="js/jquery.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.serialize-object.min.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->

</body>
</html>

JS代码:

var $form = $('form#bookingForm'),
    url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'

function disableAll() {
    $('#c-rail-yes').attr('required', false).attr('disabled', true);
    $('#c-rail-no').attr('required', false).attr('disabled', true);
    $('#craftName').attr('required', false).attr('disabled', true);
    $('#bizName').attr('required', false).attr('disabled', true);
    $('#insurance-yes').attr('required', false).attr('disabled', true);
    $('#insurance-no').attr('required', false).attr('disabled', true);
}

$('#stallType-Preloved').change(function () {
    if(this.checked) {
        disableAll();
        $('#c-rail-yes').attr('required', true).attr('disabled', false);
        $('#c-rail-no').attr('required', true).attr('disabled', false);
        $('#hosted_button_id').attr('value', '7L75UXEHSKFLG');
    }
});

$('#stallType-Craft').change(function () {
    if(this.checked) {
        disableAll();
        $('#craftName').attr('required', true).attr('disabled', false);
        $('#hosted_button_id').attr('value', 'HFTF3KS5T2ETA');
    }
});

$('#stallType-Business').change(function () {
    if(this.checked) {
        disableAll();
        $('#bizName').attr('required', true).attr('disabled', false);
        $('#insurance-yes').attr('required', true).attr('disabled', false);
        $('#insurance-no').attr('required', true).attr('disabled', false);
        $('#hosted_button_id').attr('value', '48R67JG4F7H4J');
    }
});

$('#submit-form').on('click', function(e) {
    var valid = this.form.checkValidity();
    if (valid) {
        e.preventDefault();
        var jqxhr = $.ajax({
            url: url,
            method: "GET",
            dataType: "json",
            dataType: "json",
            data: $form.serializeObject(),
            beforeSend: function (key,value) {
                return (value == undefined) ? "" : value
            },
            success: function () {
                $('#redirect_page').modal('show');
                $('#bookingForm').submit();
            }
        });
    }
});

我尝试使用beforeSend,但这似乎没有任何效果。

1 个答案:

答案 0 :(得分:0)

假设表单中没有嵌套对象,您只需在发送对象元素之前循环它们

let jsObj = $form.serializeObject();

Object.keys(jsObj).forEach(key => {
  jsObj[key] = jsObj[key] ? jsObj[key] : "";
})

然后你只需通过AJAX发送该对象:

$('#submit-form').on('click', function(e) {
var valid = this.form.checkValidity();
if (valid) {
    e.preventDefault();
    var jqxhr = $.ajax({
        url: url,
        method: "GET",
        dataType: "json",
        dataType: "json",
        data: jsObj,
        beforeSend: function (key,value) {
            return (value == undefined) ? "" : value
        },
        success: function () {
            $('#redirect_page').modal('show');
            $('#bookingForm').submit();
        }
    });
  }
});