如何作为ajax数据发送和接收多个选择值?

时间:2018-02-28 15:27:11

标签: ajax flask

多个可选择的选择标签的值作为ajax数据发送,并且为空。

html代码

<select id="dd" class="selectpicker" multiple data-live-search="true" data-live-search-placeholder="Search" >
<optgroup label="filter1">
 <option>option1</option>
 <option>option2</option>
 </optgroup>
<optgroup label="filter2">
 <option>option1</option>
 <option>option2</option>
</optgroup>
</select>
<select  class="selectpicker"  name ='start_y'>
 <option value="2015">2015</option>
 <option value="2014">2014</option>
 <option value="2013">2013</option>
</select>
<select class="selectpicker"  name ='end_y'>
 <option value="2015">2015</option>
 <option value="2014">2014</option>
 <option value="2013">2013</option>
</select>

<button id ="go" type="button" class="btn btn-default">Search</button>

脚本

选择标记值ajax

$(function(){
  $('#go').click(function(){
  var city = $('#dd').val();
  var start_y = $('[name=start_y]').val();
  var end_y = $('[name=end_y]').val();

  $.ajax({
    url: '/signUpUser',
    data: {city:city,start_y:start_y,end_y:end_y},
    type: 'POST',
    success: function(response){
      console.log(response);
    },
    error: function(error){
      console.log(error);
    }
  });

});
});

视图

@app.route('/signUpUser', methods=['POST'])
   def siii():
   city =  request.form.get("city")
   start_y = request.form.get("start_y")
   end_y = request.form.get("end_y")
   return json.dumps({'city':city,'start_y':start_y,'end_y':end_y})

结果

{"city":"null", "start_y":"2015", "end_y":"2016",} 

仅选择多个值时选择为空

???????

1 个答案:

答案 0 :(得分:1)

jQuery ajax使用PHP样式序列化,这意味着将附加一个数组参数并附加[]。为了避免在请求中将传统设置为true。

$.ajax({
  url: '/signUpUser',
  data: {city:city,start_y:start_y,end_y:end_y},
  type: 'POST',
  traditional: true,
  success: function(response){
    console.log(response);
  },
  error: function(error){
    console.log(error);
  }
});