【问题标题】:multiple select field pass ajax data as string多个选择字段将ajax数据作为字符串传递
【发布时间】:2020-06-04 15:05:43
【问题描述】:

我的问题是数量值作为字符串而不是数组传递。比如["1,2"],不过我需要的是[1,2]

<div class="form-group col-md-4">
  <div class="form-group">
    <label for="title">Quantity:</label>
    <select name="quantity[]" id="quantity" class="form-control" multiple>
    </select>
  </div>
// get the quantity value:
if (res) {
  $("#quantity").empty();
  $.each(res, function(key, value) {
    $("#quantity").append('<option value="' + key + '">' + value + '</option>');
  });
} else {
  $("#quantity").empty();
}

// pass the quantity value:
var quantity = new Array(); //storing the selected values inside an array
$('#quantity :selected').each(function(i, selected) {
  quantity[i] = $(selected).val();
});

$.ajax({
  type: "POST",
  url: "{{route('localBook.store')}}?quantity[]=" + quantity,
  dataType: 'json',
  data: form_data,
  success: function(res) {}
});

【问题讨论】:

  • 为什么要在 url 中而不是在 data 字段中发送它?这样会更容易
  • b/c 我想传递对象“form_data”。 if t do data:{quanity:quanity, form_data} 对象变为字符串(1 行,如 name=&type_of_organization=&city_id=&type=Room&start);
  • 发生这种情况是因为您刚刚将form_data 放入数据字段,但忘记定义标识符identifier: variable => form_data: form_data

标签: jquery ajax laravel


【解决方案1】:

我认为发生这种情况是因为您将数量数组作为 url 参数传递,而不是在 http 正文中传递它(如 post 请求中所预期的那样)。如果您想执行 POST 请求,这是多余的。

编辑您的请求,通过 ajax 请求中的数据字段传递数据,一切都会正常工作。 :)

$.ajax({
  type: "POST",
  url: "{{route('localBook.store')}}",
  dataType: 'json',
  data: {
    quantity: this.quantity
  },
  success: function(res) {}
});

干杯,

尼克拉斯

【讨论】:

  • 谢谢,Niklas 的快速响应数量工作正常,但我使用 url 来传递数据中的 form_data。当我使用数据时:{form_data,数量:数量}。单行中的 form_quantity 值。如何克服这个问题
  • 现在:form_data:"name=&type_of_organization=&city_id=&type=Room&start_price=300+ETB+-+&end_price=10000……之前:name:null,type_of_organization:null,city_id:“68”,输入:“房间”,如何更改为对象
  • 您可以通过请求(数据字段)传递多个值,例如:data { quantity: this quantity, form_data: form_data },
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多