简体   繁体   English

使用Ajax提交表单

[英]Submit a form using Ajax

First, here is my code : 首先,这是我的代码:

routes.php routes.php

$router->resource('vips','formController');

formController.php (im only posting the concerned function) formController.php (仅发布相关功能)

public function store(CreateVipRequest $request, Vip $vip, Pool $pool, Url $url)
{
    $new_vip = $vip->create($request->except(['srv_hostname', 'srv_ip', 'srv_port','url']));
    $pool->fill($request->only(['srv_hostname', 'srv_ip', 'srv_port']));
    $url->fill($request->only(['url']));

     /* Some more inserts on the database...*/

    return redirect()->route('vips.show', [DB::table('vips')->max('id')]);
}

My code submits the form, and after some json requests to a distant Api (and some databases insertions) it redirects to the show view. 我的代码提交了表单,并在向远处的Api(和某些数据库插入)请求了json后,将其重定向到show视图。

Now I want to add a second button that submits the form via Ajax. 现在,我想添加第二个按钮,该按钮通过Ajax提交表单。

Question : Is there a way to use the same function store ? 问题 :是否可以使用相同的功能store I need it to be able to process both an ajax submit and a normal submit. 我需要它能够处理ajax提交和普通提交。

Submit form using ajax 使用ajax提交表单

$("#form-name").submit(function(ev){
  ev.preventDefault();  
  var formURL = $(this).attr("action");
  var postData = $(this).serializeArray(); 
  $.ajax({
    url: formURL,
    type: 'POST',
    data: postData,
    success: function(data, textStatus, jqXHR){
      location.reload();
    },
    error: function(jqXHR, textStatus, errorThrown){
      var errResponse = JSON.parse(jqXHR.responseText);
    },
  });
});

Yes, you can. 是的你可以。

In your javascript you can do something like this (assuming you're using jquery): 在您的JavaScript中,您可以执行以下操作(假设您使用的是jquery):

// if you're using a form
var data = $('form').serialize();

// if data comes from elsewhere
var data = {foo: 'bar', ...};

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  dataType: 'json',
  success: function (data) {
    // Do something if everything went fine
  },
  error: function (jqXHR, textStatus, errorThrown) {
    // Do something if something went wrong
  },
});

Your controller will catch the data coming from the request as you are already doing. 您的控制器将像您已经做的那样捕获来自请求的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM