如何在JQuery AJAX表单提交中指定数据字段?

时间:2018-09-28 21:54:57

标签: javascript jquery ajax laravel laravel-5

我需要HTML表单数据通过JQuery AJAX POST请求到达服务器,其格式与正常提交的表单完全相同。 我尝试使用$ .serialize()和$ .serializeArray(),但都没有给出简单的

$('#booking-form').on('submit', function(e) {
   var formdata = $(this).serialize();
   // process data and send ajax request
   console.log(formdata);

   $.ajax({
       headers: { 'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val() },
       type: 'POST',
       url: 'book',
       data: { data: formdata },
       success: function (data)
           {
           // Redirect to booking confirmation page:
           if(data.response == 'ok') window.location.replace(data.url);
           else alert('Card payment failed)
           },
       error: function (data) // Server error
           {
           console.log('Error:', data.responseText);
           }
       });

    // Prevent form submit.
    return false;
});

后端是Laravel(5.4),但我认为这不是Laravel特有的问题。记录一个正常的表单提交会给出:

array (
  'code' => '2ZSSAVGXAHMOOKGOC0SC',
  'ownername' => 'My Name',
  'housestreet' => '12 Any street, London',
  'city' => 'London',
  'ownerpcode' => 'ZipCode Here',
  'phone' => '1234567890'
)

这就是我追求的结构。但是上面的代码给出了:

array (
  'data' => 'code=BUH1HGXDWW84SWGWSO84&ownername=My+Name&housestreet=12+Any+street%2C+London&city=London&ownerpcode=Zipcode+here&phone=1234567890')

或使用$ .serializeArray()给出:

array (
  'data' => 
  array (
    0 => 
    array (
      'name' => 'code',
      'value' => 'CC22DPHQ2F40G0GCKKK0',
    ),
    2 => 
    array (
      'name' => 'ownername',
      'value' => 'My Name',
    ),
    3 => 
    array (
      'name' => 'housestreet',
      'value' => '12 Any street, London',
    ),
etc.

如何通过AJAX(使用JQuery或纯JS)在服务器上以正确的格式获取数据? 我无法将表单字段手动编码到数据中:$ .ajax调用中的参数,因为其中一些是在服务器上动态生成的,而某些则是由前端的JS动态生成的,其中包括供PHP解析的数组字段(例如表单字段name="item[0][extra][]"

谢谢

1 个答案:

答案 0 :(得分:0)

这是我用来序列化通过ajax发送的标准表格的功能;

function serializeForm(formSelector) {
  var o = {};
  var a = $(formSelector).serializeArray();
  $.each(a, function() {
    if (o[this.name] !== undefined) {
      if ($("input[name='" + this.name + "'][type='checkbox']").length <= 0) { //stupid checkboxes
        if (!o[this.name].push) {
          o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
      }
    } else {
      o[this.name] = this.value || '';
    }
  });
  return o;
}

//it could be used like this
$("input").change(function(){console.log(serializeForm("form"))});
//or this
$.ajax({
  //...snip...
  data: serializeForm("form"),
  //...snip...
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" name="testField" value="lorem ipsum" />
</form>