【问题标题】:Sent Form Data from View to Controller using AJAX使用 AJAX 将表单数据从视图发送到控制器
【发布时间】:2016-03-21 17:10:55
【问题描述】:

我有一个表单和一个保存按钮。单击时,我想使用 Ajax 将表单中的所有数据发布到我的Controller。我本可以使用Input::all() 来做到这一点,但我试图避免我的页面刷新

我希望能够访问这些表单数据,就像 input::all(),但使用 Ajax 代替。

如何进行和实施这样的事情?


我试过了

JS

$('.saveRateLimitBTN').click(function (event) {

    var url = '{{env("APP_URL")}}{{$cpe_mac}}'+'/device/'+'{{$device_mac}}'+'/rate/update';

    var inputs = {};
    $("#editRateLimitForm :input").each(function() {
        inputs[$(this).attr("name")] = $(this).val();
    });

    $.ajax({
        url: url,
        type: 'PUT',
        dataType: 'json',
        data: inputs,
        success: function (data, textStatus, xhr) {
            console.log(data);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('PUT error.', xhr, textStatus, errorThrown);
        }
    });

});

DeviceController > updateRate() 函数

public function updateRate(){

        dd('Here'); // This never get run.
}

路线

Route::put('{cpe_mac}/device/{device_mac}/rate/update',['as'=>'device.update', 'uses'=>'DeviceController@updateRate']);

表单(刀片语法)

{!! Form::open(array('url' => '/'.$cpe_mac.'/device/'.$device_mac.'/rate/update', 'class' => 'form-horizontal', 'role' =>'form','method' => 'PUT', 'id' => 'editRateLimitForm')) !!}

        <span class="pull-left">
            <div class="col-sm-6">
                <p>Downlink </p>
                <select type="text" id="rateDownSelect" class="form-control" name="max_down" >

                    @foreach ($rate_limit as $key => $value)
                    <option value="{{$value or ''}}"
                    >{{$value or ''}} Kbps</option>
                    @endforeach
                </select>
            </div>
            <div class="col-sm-6">
                <p>Uplink</p>
                <select type="text" id="rateUpSelect" class="form-control" name="max_up" >
                    @foreach ($rate_limit as $key => $value)
                    <option value="{{$value or ''}}">{{$value or ''}} Kbps</option>
                    @endforeach
                </select>
            </div>
        </span><br>


        {!! Form::hidden('cpe_mac', $cpe_mac)!!}
        {!! Form::hidden('device_mac', $device_mac)!!}



        <span class="pull-right">
            <button class="saveRateLimitBTN btn btn-xs btn-info pull-right" type="button">Save</button>
        </span>


{!! Form::close();!!}

结果

XMLHttpRequest 无法加载 http://localhost/000D6751560C/device/0800277B6BDE/rate/update。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:8888' 因此不允许访问。

【问题讨论】:

    标签: php jquery ajax laravel laravel-5


    【解决方案1】:

    像下面这样序列化表单以访问所有类型的表单字段值。

    $( "form" ).on( "submit", function( event ) {
      event.preventDefault();
      console.log( $( this ).serialize() );
      // Your Ajax here !
    });
    

    有用的网址:
    https://api.jquery.com/serializeArray/
    https://api.jquery.com/serialize/

    【讨论】:

    • 我试过$( "#editRateLimitForm" ).on( "submit", function( event ) { event.preventDefault(); console.log( $( this ).serialize() ); // Nothing printing out }); 没有打印出来! :(
    • 你有表单标签吗?也请分享html代码。
    • 通过添加输入类型=提交按钮而不是保留按钮进行测试
    • 检查 jsfiddle 网址 - jsfiddle.net/0br4qcgg/1 将在 4 - 5 小时后看到休息 :) 这里是上午 1.10
    • 把按钮改成type=submit,我现在看到了序列化数据。我怎样才能让他们吐出一个数组/对象呢?
    【解决方案2】:

    @ihue 不要使用我在其他 cmets 中使用的 .serialize(),而是使用 .serializeArray() 来获取 PUT 请求的数据对象。但是根据您的错误,这里的另一个问题是您无法将 ajax 请求从一个域发送到另一个域。它说你在 localhost:8888 并且正在向 localhost 发送请求,这是一个不同的域。

    尝试将 AJAX 请求更改为转到http://localhost:8888/[yourURL],而不是使用相对的/[yourURL],看看是否会有所不同。

    如果这不起作用,您需要在 Laravel API 中允许 CORS(跨域请求共享)。这里有一些关于 CORS 的信息http://www.html5rocks.com/en/tutorials/cors/,这里有一个 Laravel 包来帮助处理它https://github.com/barryvdh/laravel-cors

    【讨论】:

    • 感谢更新,我会继续关注您的问题
    • 查看我的编辑 - 根据您收到的错误,这是一个 CORS 问题
    • 感谢您的回答!我现在就试试这些建议。我在控制器中的功能似乎没有得到执行。你知道为什么吗?
    【解决方案3】:

    您的 APP_URL 可能设置为 http://localhost 但您的应用程序的当前 url 是 http://localhost:8888 。因此,它被视为跨域请求,您需要通过添加此 htaccess 文件来允许跨域请求:

    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
    

    理想情况下您应该做的其他解决方案是像这样更改您的 AJAX url:

    var url = '{{ url($cpe_mac."/device/".$device_mac."/rate/update") }}';
    

    这将使用您当前用于访问您的网站的 url 定义 AJAX url。

    【讨论】:

      猜你喜欢
      • 2014-12-06
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      相关资源
      最近更新 更多