从表单中检索的Ajax序列化数据中设置JSON数据

时间:2015-05-05 17:43:47

标签: javascript jquery ajax json

这是我的html表单:

<form role="form" id="booking" class="form-horizontal" action="booking.json" method="POST">
                <div class="form-group">
                    <label for="destination">Destination:</label>
                    <select id="destination" name="destination" class="form-control" title="Select your Destination...">
                        <option value="Dominican Republic">dominican</option>
                        <option value="Miami, Florida">miami</option>
                        <option value="Las Vegas, Nevada">vegas</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="quantity">Nights:</label>
                    <input type="number" id="quantity" name="quantity" value="1">
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-default text-uppercase">Book Trip</button>
                </div>
                <div class="form-submitted" style="display: none">
                </div>
            </form>

这是我的Ajax:

$.ajax( form.attr('action'), {
        timeout: 3000,
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: form.serialize(),
        beforeSend: function () {
            $('.booking-flight').addClass("spinner");
        },
        complete: function () {
            $('.booking-flight').removeClass("spinner");
        },
        error: function (request, errorType, errorMessage) {
            alert(errorMessage);
        },
        success: function (response) {
            console.log($('form').serialize());
            form.remove();
            var msg = $("<p></p>");
            msg.append("Destination: " + response.destination);
            msg.append("Nights: " + response.quantity);
            $('.booking-flight').hide().html(msg).fadeIn();
        }
    });

这是我的JSON文件,其中包含我设置的随机信息:

{
  "destination": "Dominican Republic",
  "totalPrice": 199.99,
  "quantity": 5,
  "confirmation": 234235
};

如何检索我从Ajax发送的序列化数据并将其设置为我的JSON文件...这样我从表单中获取了正确的数据?

2 个答案:

答案 0 :(得分:0)

您可以使用json_decode($user_json_data)

json_decode($user_json_data)将返回一个对象

json_decode($user_json_data,TRUE)会返回一个数组

答案 1 :(得分:0)

您可以使用jQuery函数.serializeArray();,然后按照此处所述操作响应:https://stackoverflow.com/a/1186309/507384