jQuery preventDefault正在刷新页面并以数组形式显示JSON-如何将这些数据恢复为相同格式?

时间:2018-10-10 10:41:46

标签: javascript jquery

我正在创建一个Flask应用程序,该应用程序从SQL中获取数据,对其进行json化,并在提交时返回JSON数组。

{"DoorType":"33PAL","FifthWheelHeight":"1000","FrontTensioner":"R61","NeckDepth":"158","POD":"No","RearPillarCodeNS":"N/S-Variable-R100-No-N/A-CS3/FS1/FS2-No-N/A-Barn or Flush Doors","RearPillarNS":"4RB-1385","RearPillarOS":"4RB-1386","RearTensioner":"R100","StrapStorage":"No","Wraps":"No","myList":[3583,3960,3960,3983,3990,4000,4001,4006,4030,4118,4120,4160,4160,4170,4170,4178,4183,4190,4200,4218,4228,4230,4240,4260,4285,4310,4333,4360,4360,4370,4380,4380,4383,4385,4410,4410,4415,4435,4440,4440,4450,4458,4460,4460,4470,4483,4485,4510,4518,4530,4530,4560,4560,4583,4590,4603,4610,4620,4660,4708]}

我的问题是,我的HTML页面中有js,这应该防止我的页面重新加载,并将JSON信息返回给我的选择标签,但是页面会重新加载并提供该数组。

我的问题是,如何阻止它重新加载页面,并使该数组转换回selects。这样做的原因是需要为我的<select>{% for elem in myList%} <option> {{elem}} </option> {% endfor %}</select>填写表单(因为它基于输入和SQL获取数据,并进行计算得出可以放入此标记的列表。< / strong>

我的html页面如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>CS3 Curtainsider Dimensions</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="http://code.jquery.com/jquery-2.0.2.min.js " type="text/javascript"></script>
</head>
<body>

<div class="jumbotron text-center">
  <h1>CS3 Curtainsider Dimensions</h1>
</div>

<form method="POST">
<fieldset>
    <div class="col-sm-3">
        <label for="DoorType"> Door Type</label>
  <select class="form-control" name="DoorType" id="DoorType">
      <option value="33PAL">33PAL</option>
      <option value="34PAL">34PAL</option>
  </select>
        <label for="RearTensioner"> Rear Curtain Tensioner</label>
  <select class="form-control" name="RearTensioner">
      <option value="R100">R100</option>
      <option value="R52">R52</option>
      <option value="R44">R44</option>
  </select>
        <label for="FrontTensioner"> Front Curtain Tensioner</label>
   <select class="form-control" name="FrontTensioner">
      <option value="R61">R61</option>
      <option value="R33">R33</option>
  </select>
        <label for="StrapStorage"> Strap Storage Required</label>
    <select class="form-control" name="StrapStorage" id="StrapStorage">
      <option value="No">No</option>
      <option value="Yes">Yes</option>
    </select>
        <label for="POD"> POD Required</label>
    <select class="form-control" name="POD">
      <option value="No">No</option>
      <option value="Yes">Yes</option>
    </select>
        <label for="Wraps"> Curtain Wraps Required</label>
    <select class="form-control" name="Wraps">
      <option value="No">No</option>
      <option value="Yes">Yes</option>
    </select>
        <label for="FifthWheelHeight"> Fifth Wheel Height</label>
    <select class="form-control" name="FifthWheelHeight" id="FifthWheelHeight">
      <option value="1000">1000</option>
      <option value="1200">1200</option>
      <option value="1250">1250</option>
      <option value="1300">1300</option>
    </select>
    <label for="Neck Depth"> Neck Depth</label>
    <select class="form-control" name="NeckDepth" id="NeckDepth">
      <option value="158">158</option>
      <option value="160">160</option>
      <option value="163">163</option>

    </select>

    <select class="form-control" name="option[2]" id="option[2]">
    <option value="115">Standard Cantrail</option>
    <option value="80">Slimline Cantrail</option>
</select>
        <input type="submit" value="Calculate Available Overall Heights" class="btn btn-danger btn-sm" id="button" name="button">
    <br>
    </div>
<div id="response">
    <select>
    {% for elem in myList%}
        <option> {{elem}} </option>
        {% endfor %}
    </select>

</div>

</fieldset>
</form>


<script>

$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
    $.ajax({
      url: '/Dimensions',
      data: $('form').serialize(),
      datatype: 'json',
      type: 'POST',
      success: function (response) {
    $('#response').empty()
        $.each(response[0], function (i) {
            $('#response').append($('<div>').append(
                //standard columns for all trailers
                $('<div>').text(response[0][i].FifthWheelHeight)))
        })
      }
})


</script>

</body>
</html>

我的python应用程序如下:(注意config是一个仅包含我的类和连接详细信息的文件)

from config import *

@app.route('/Dimensions', methods=['GET', 'POST'])
def Dimensions():
    if request.method == 'POST':
        DoorType = request.form['DoorType']
        RearTensioner = request.form['RearTensioner']
        FrontTensioner = request.form['FrontTensioner']
        POD = request.form['POD']
        Wraps = request.form['Wraps']
        NeckDepth = request.form['NeckDepth']
        FifthWheelHeight = request.form['FifthWheelHeight']
        StrapStorage = request.form['StrapStorage']

        RearPillarCodeNS = 'N/S-Variable-' + RearTensioner + '-No-N/A-' + 'CS3/FS1/FS2-No-N/A-Barn or Flush Doors'
        RearPillarCodeOS = 'O/S-Variable-' + RearTensioner + '-No-N/A-' + 'CS3/FS1/FS2-No-N/A-Barn or Flush Doors'

        RearPillarNS = db_session3.query(ConfiguratorRearPillar.PartNumber) \
            .filter(cast(ConfiguratorRearPillar.Code, VARCHAR).like(f'%{RearPillarCodeNS}%')) \
            .all()[0][0]
        RearPillarOS = db_session3.query(ConfiguratorRearPillar.PartNumber) \
            .filter(cast(ConfiguratorRearPillar.Code, VARCHAR).like(f'%{RearPillarCodeOS}%')) \
            .all()[0][0]

        LISTOFLENGTHSONLY = db_session2.execute('ConfiguratorRearPillarLengthsOnly :p1',
                                                {'p1': RearPillarNS}).fetchall()
        L2 = []
        for item in LISTOFLENGTHSONLY:
            L2.append(int(item[0]))

        AvailableOverallHeights = list(map(lambda x: x+int(NeckDepth)+int(FifthWheelHeight), L2))

        return jsonify(DoorType=DoorType, RearTensioner=RearTensioner,
                               StrapStorage=StrapStorage, FrontTensioner=FrontTensioner, POD=POD, Wraps=Wraps,
                               NeckDepth=NeckDepth, FifthWheelHeight=FifthWheelHeight,
                               RearPillarCodeNS=RearPillarCodeNS, RearPillarNS=RearPillarNS,
                               RearPillarOS=RearPillarOS, myList=AvailableOverallHeights)
    else:

        return render_template('Dimensions.html')

一如既往,我们将不胜感激任何帮助。

2 个答案:

答案 0 :(得分:0)

尝试使用type="button"代替type="submit"

答案 1 :(得分:0)

您的提交处理程序肯定应该可以工作。据我了解,您必须从json响应中获取myList并将其添加到表单中以进行进一步操作。另外,其他参数可以更改,因此您也必须更新表单选择。我认为这应该可行:

// Simplified response
var response = {
  "DoorType": "34PAL",
  "FifthWheelHeight": "1000",
  "StrapStorage": "No",
  "Wraps": "No",
  "myList": [3583, 3960, 4590, 4603, 4610, 4620, 4660, 4708]
};

$("form").on("submit", function(event) {
  $targetElement = $('#response')
  if ($targetElement.children().length == 0) {
    // There's no select element
    event.preventDefault();

    // Perform ajax call
    // FAKE AJAX CALL
    console.log("Sending data: " + $(this).serialize());
    // Success handler
    for (key in response) {
      if (key == 'myList') {
        // Add the new elements from 'myList' to the form
        $targetElement.empty();
        select = $('<select></select>');
        response[key].forEach(function(item) {
          select.append($('<option>').text(item));
        })

        $targetElement.html(select);
      } else {
        // Update existing controls to those of the response. 
        // You can check if value has changed beforehand.
        $(':input[name="' + key + '"]').val(response[key]);
      }
    }

    // End handler
  }
  // Proceed with normal submission or new ajax call
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-2.0.2.min.js " type="text/javascript"></script>
</head>

<body>

  <div class="jumbotron text-center">
    <h1>CS3 Curtainsider Dimensions</h1>
  </div>

  <form method="POST">
    <fieldset>
      <div class="col-sm-3">
        <label for="DoorType"> Door Type</label>
        <select class="form-control" name="DoorType" id="DoorType">
          <option value="33PAL">33PAL</option>
          <option value="34PAL">34PAL</option>
        </select>

        <!-- Elements omitted -->

        <input type="submit" value="Calculate Available Overall Heights" class="btn btn-danger btn-sm" id="button" name="button">
        <br>
      </div>

      <div id="response">
        <!-- Empty element until form submitted-->
      </div>

    </fieldset>
  </form>