使用AJAX将表单数据从View发送到Controller

时间:2015-12-15 18:56:09

标签: php jquery ajax laravel laravel-5

我有一个表单和一个保存按钮。点击后,我想使用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”标头。因此,不允许原点“http://localhost:8888”访问。

3 个答案:

答案 0 :(得分:2)

如下所示序列化表单以访问所有类型的表单字段值。

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

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

答案 1 :(得分:1)

@ihue使用.serialize()来获取PUT请求的数据对象,而不是使用我在其他注释中使用的.serializeArray()。但是,基于您的错误,此处的另一个问题是您无法将ajax请求从一个域发送到另一个域。它表示你在localhost:8888并且正在向localhost发送请求,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

答案 2 :(得分:0)

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

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

其他解决方案,您理想情况下应该更改您的AJAX网址:

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

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

相关问题