【问题标题】:Get empty string not null in Ajax in Laravel在 Laravel 的 Ajax 中获取不为空的空字符串
【发布时间】:2021-07-10 08:50:43
【问题描述】:

我在 Laravel 中使用 Ajax,每当调用 Ajax 时,输入字段值(为空字符串)都会转换为空值。但我想要空字符串作为回应。我怎样才能得到这个? 我知道我可以映射这些值并将空值转换/设置为空字符串,但效率不高。

我的 Ajax 代码:

$('#settingsForm').on('submit',(e) => {
  e.preventDefault();
  $.LoadingOverlay("show");
  const id = $('#id').val();
  const data = new FormData($('#settingsForm')[0]);
  $.ajax({
    type:'POST',
    url:  "{{url('company/settings')}}"+'/'+id,
    processData: false,
    contentType: false, 
    data: data,
    beforeSend: ()=>{
      console.log(data);
    },
    success: (resp) => {
      if(resp.code == 200){
        toastr.success(resp.type,resp.msg);
      }else
        toastr.error(resp.type,resp.msg);
      $.LoadingOverlay("hide");
    }
  });
  $('#tableRow').show();
  $('#settingsDiv').hide();
})

【问题讨论】:

    标签: ajax laravel form-data


    【解决方案1】:

    您可以像这样为每个值使用 getter:

    public function getNameAttribute($value){
        return $value ?? '';
    }
    
    

    然后使用toArray()toJson() 方法你的空值将被转换成一个空字符串

    【讨论】:

      猜你喜欢
      • 2014-03-23
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2021-10-18
      • 2012-06-07
      • 1970-01-01
      • 2017-07-23
      相关资源
      最近更新 更多