【问题标题】:ajax result success nullajax结果成功null
【发布时间】:2019-07-23 22:21:31
【问题描述】:

我试图弄清楚为什么我的成功的 ajax 警报从我的控制器返回 null。

我只是序列化一个表单,将它提交给控制器并解析它以获得数组分解。

ajax 是成功的,因为警报被触发,但数据,应该是结果数组,在警报中实际上是 null。

我做错了什么?

view.blade

<form id="codeGeneration">
<?php $i = 1; ?>
@foreach($getRuleAttributes as $attributes)
@if($attributes->title == 'New')
    <tr>
        <td><input type="checkbox" name="attribute[{{$i}}]['checked']"></td>
        <td><label>{{ $attributes->title }}</label></td>
        <input type="hidden" name="attribute[{{$i}}]['attributet_id']" value="{{ $attributes->attributet_id }}">
        <input type="hidden" name="attribute[{{$i}}]['attribute_data']" value="0">
        <input type="hidden" name="attribute[{{$i}}]['attribute_type']" value="promo_codes">
    </tr>
@else
    <tr>
        <td><input type="checkbox" name="attribute[{{$i}}]['checked']"></td>
        <td><label>{{ $attributes->title }}</label></td>
        <td><input type="text" name="attribute[{{$i}}]['attribute_data']"></td>
        <input type="hidden" name="attribute[{{$i}}]['attributet_id']" value="{{ $attributes->attributet_id }}">
        <input type="hidden" name="attribute[{{$i}}]['attribute_type']" value="promo_codes">
    </tr>
@endif
<?php $i++; ?>
@endforeach
</form>

//ajax
var form_data = $("#codeGeneration").serialize();
    $.ajax({
       type:'POST',
       url:'savePromoInfo',
       data:{form_data:form_data},
        _token: '{{ csrf_token() }}',
        success: function(data){
          alert(data);
        }
    });

控制器

public function savePromoInfo()
{
    $form_data = $request->form_data;
    parse_str($form_data, $my_array_of_vars);
    $attr = $my_array_of_vars['attribute'];

    return json_encode($attr);
}

【问题讨论】:

    标签: javascript html ajax laravel


    【解决方案1】:

    真的成功了吗?您可以尝试作为第一行返回“Ok”吗?例如,以确保通过。

    我还注意到您从 ajax 中的数据中发送了令牌,但这应该是 data 对象的一部分。

    data:{form_data:form_data, _token: "{{ csrf_token() }}"},
    

    【讨论】:

    • 是的,如果我在成功中输入 ok,那么它会正确返回
    • 如果你只使用return $attr;会有什么反应?
    • 它不再为空,但那里什么都没有,基本上是一个空警报
    • 尝试将结果转储到控制台而不是警报中,这可能没有正确解析对象。所以在成功回调中使用console.log(data)
    • 好的,控制台显示它正在收到响应,但它也是空的。但是如果我多次点击按钮,它会在控制台中显示每个按钮调用
    猜你喜欢
    • 2013-07-25
    • 2011-11-18
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2011-03-19
    相关资源
    最近更新 更多