使用Laravel 5.1中的VueJs和AJAX提交表单

时间:2022-11-24 14:50:25

I am trying to submit a form using AJAX and VueJs. But somehow I am failing to achieve that. I always end up getting an empty Illuminate\Http\Request object.

我正在尝试使用AJAX和VueJs提交表单。但不知何故,我未能实现这一目标。我总是得到一个空的Illuminate \ Http \ Request对象。

The blade file:

刀片文件:

<body>
    <div class="container">
        <generate-admin></generate-admin>
    </div>

    <script src="https:http://code.jquery.com/jquery.js"></script>
    <script src="{{ url('/js/main.js') }}"></script>
</body>

The component:

<template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

        <div class="form-group">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

        </div>

        <input type="submit" value="Submit">

    </form>
</template>

<script>
    export default {
        data: function() {
            return {
                username: ''
            }
        },

        methods: {
            createAdministrator: function() {
                formContents = jQuery("#createAdministrator").serialize();

                this.$http.post('/admin', formContents).then(function(response, status, request) {
                    console.log(response);
                }, function() {
                    console.log('failed');
                });
            }
        }
    }
</script>

main.js

import Vue from 'vue';
import GenerateAdmin from './components/GenerateAdmin.vue';

var VueResource = require('vue-resource')
Vue.use(VueResource);

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
Vue.http.options.emulateJSON = true;

new Vue({
    el: 'body',

    components: { GenerateAdmin }
});

gulpfile.js

var elixir = require('laravel-elixir');

require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
});

routes.php

Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function(Request $request) {
    // returns an empty object.
    return response(['results' => $request]);
});

Route::get('/', function () {
    return view('welcome');
});

What I get in return is:

我得到的回报是:

"{"results":{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}}"

When I check the Request Payload section of Network Tab in Chrome. I do see that the form is getting submitted successfully with whatever data I write in the text box above.

当我检查Chrome中的“网络标签”的“请求有效负载”部分时。我确实看到表单已成功提交,我在上面的文本框中写了任何数据。

Why is this happening ? Kindly guide me where I have made the mistake ?

为什么会这样?请指导我在哪里弄错了?


UPDATE 1:

I was playing trial and error with the code above. And I removed the namespace Illuminate\Http\Request and also removed the argument Request $request from the post Route. And changed the passing parameter to object from string.

我正在使用上面的代码进行试验和错误。我删除了命名空间Illuminate \ Http \ Request,并从路径后删除了参数Request $ request。并将传递参数从字符串更改为对象。

Doing so, did the job for me that I was looking for. Why I don't know. I am still looking for someone who can explain this to me.

这样做,为我做了我正在寻找的工作。为什么我不知道。我仍在寻找可以向我解释的人。

Why adding the namespace Iluminate\Http\Request in routes.php file didn't work as I was expecting and removing it did the task ?

为什么在routes.php文件中添加命名空间Iluminate \ Http \ Request并不像我期望的那样工作并删除它完成了任务?

Can anybody tell me why it didn't worked out earlier ? Any kind of help is highly appreciated.

任何人都可以告诉我为什么它没有早点解决?任何形式的帮助都非常感谢。


P.S.: I have started learning VueJs Components recently.

P.S。:我最近开始学习VueJs Components。

2 个解决方案

#1


2  

As a general practice I follow, any form data which needs to be passed to the laravel controller is passed as json object from vue frontend. Then in laravel controller (route with a closure function in your case) the values from the received json object are retrieved by using $request->get('key').
So in your case the component code could be

作为我遵循的一般做法,任何需要传递给laravel控制器的表单数据都作为json对象从vue前端传递。然后在laravel控制器(在你的情况下带有闭包函数的路由)中,使用$ request-> get('key')检索接收到的json对象的值。所以在你的情况下组件代码可以是

    <template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

        <div class="form-group">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

        </div>

        <input type="submit" value="Submit">

    </form>
</template>

<script>
    export default{
      template:require('./generate-admin-template.html'),
      data() {
          return {
              username: ''
          }
      },
      computed:{
        formData(){
          return {
            username:this.username
          }
        }
      },
      methods: {
          createAdministrator: function() {
              this.$http.post('/admin', this.formData).then(function(response) {
                  console.log(response);
              }, function() {
                  console.log('failed');
              });
          }
      }
    }
</script>

Then in your routes.php file

然后在routes.php文件中

<?php
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function (Request $request) {
    return response(['results' => $request->get('username')]);
});  

I guess the Illuminate\Http\Request instance returns a $request - Collection so we need to access the values using Methods available on Collections.
I have tested the above code along with your code for main.js and '/admin/create'.
One more thing - I think if you send serialized form data to the controller, then within the controller it needs to be de-serialized in order to get object or array containing $key=>$value pairs to facilitate fetching required data.

我猜Illuminate \ Http \ Request实例返回$ request - Collection,因此我们需要使用Collections上可用的方法来访问这些值。我已经测试了上面的代码以及main.js和'/ admin / create'的代码。还有一件事 - 我认为如果您将序列化的表单数据发送到控制器,那么在控制器中需要对其进行反序列化以获取包含$ key => $ value对的对象或数组,以便于获取所需的数据。

#2


0  

All variables ($attributes, $request, $query, etc) on Request and SymfonyRequest classes are protected, since neither class implements __toString, php does its best to give you what it can.

Request和SymfonyRequest类上的所有变量($ attributes,$ request,$ query等)都受到保护,因为这两个类都没有实现__toString,php会尽力为您提供它所能提供的功能。

If you need to see each value, you need to call correct getter. Something like:

如果您需要查看每个值,则需要调用正确的getter。就像是:

Route::post('/admin', function(Request $request) {    
    return response(['server' => $request->server(), 'form'=>$request->all()]);
});

#1


2  

As a general practice I follow, any form data which needs to be passed to the laravel controller is passed as json object from vue frontend. Then in laravel controller (route with a closure function in your case) the values from the received json object are retrieved by using $request->get('key').
So in your case the component code could be

作为我遵循的一般做法,任何需要传递给laravel控制器的表单数据都作为json对象从vue前端传递。然后在laravel控制器(在你的情况下带有闭包函数的路由)中,使用$ request-> get('key')检索接收到的json对象的值。所以在你的情况下组件代码可以是

    <template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

        <div class="form-group">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

        </div>

        <input type="submit" value="Submit">

    </form>
</template>

<script>
    export default{
      template:require('./generate-admin-template.html'),
      data() {
          return {
              username: ''
          }
      },
      computed:{
        formData(){
          return {
            username:this.username
          }
        }
      },
      methods: {
          createAdministrator: function() {
              this.$http.post('/admin', this.formData).then(function(response) {
                  console.log(response);
              }, function() {
                  console.log('failed');
              });
          }
      }
    }
</script>

Then in your routes.php file

然后在routes.php文件中

<?php
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function (Request $request) {
    return response(['results' => $request->get('username')]);
});  

I guess the Illuminate\Http\Request instance returns a $request - Collection so we need to access the values using Methods available on Collections.
I have tested the above code along with your code for main.js and '/admin/create'.
One more thing - I think if you send serialized form data to the controller, then within the controller it needs to be de-serialized in order to get object or array containing $key=>$value pairs to facilitate fetching required data.

我猜Illuminate \ Http \ Request实例返回$ request - Collection,因此我们需要使用Collections上可用的方法来访问这些值。我已经测试了上面的代码以及main.js和'/ admin / create'的代码。还有一件事 - 我认为如果您将序列化的表单数据发送到控制器,那么在控制器中需要对其进行反序列化以获取包含$ key => $ value对的对象或数组,以便于获取所需的数据。

#2


0  

All variables ($attributes, $request, $query, etc) on Request and SymfonyRequest classes are protected, since neither class implements __toString, php does its best to give you what it can.

Request和SymfonyRequest类上的所有变量($ attributes,$ request,$ query等)都受到保护,因为这两个类都没有实现__toString,php会尽力为您提供它所能提供的功能。

If you need to see each value, you need to call correct getter. Something like:

如果您需要查看每个值,则需要调用正确的getter。就像是:

Route::post('/admin', function(Request $request) {    
    return response(['server' => $request->server(), 'form'=>$request->all()]);
});