Javascript 使用 ajax 在 Vue.js 中提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31676005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:01:05  来源:igfitidea点击:

Submitting form in Vue.js with ajax

javascriptlaravelvue.js

提问by haakym

I'm really stuck on how I would work with submitting a form that makes an ajax request using Vue.js and vue-resource then using the response to fill a div.

我真的很困惑我将如何提交使用 Vue.js 和 vue-resource 发出 ajax 请求的表单,然后使用响应来填充 div。

I do this from project to project with js/jQuery like this:

我使用 js/jQuery 从一个项目到另一个项目执行此操作,如下所示:

view in blade

在刀片中查看

{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
    <div class="form-group">
        <input type="text" name="id" class="form-control" placeholder="id" required="required">
    </div>
    <button type="submit" class="btn btn-default">Search</button>
{!! Form::close() !!}

js/jquery

js/jquery

var $searchForm = $('#searchForm');
var $searchResult = $('#searchResult');

$searchForm.submit(function(e) {
    e.preventDefault() ;

    $.get(
        $searchForm.attr('action'),
        $searchForm.serialize(),
        function(data) {
            $searchResult.html(data['status']);
        }
    );
});

What I've done/tried so far in Vue.js:

到目前为止我在 Vue.js 中所做的/尝试的:

view in blade

在刀片中查看

{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
    <div class="form-group">
        <input type="text" name="id" class="form-control" placeholder="id" required="required">
    </div>
    <button type="submit" class="btn btn-default" v-on="click: search">Search</button>
{!! Form::close() !!}

vue/js

Vue/JS

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

    new Vue({
        el: '#someId',

        data: {

        },

        methods: {
            search: function(e) {
                e.preventDefault();

                var req = this.$http.get(
                    // ???, // url
                    // ???, // data
                    function (data, status, request) {
                        console.log(data);
                    }
                );
            }
        }
    });

I'm wondering if it's possible to use components when dealing with the response to output the response data to a div?

我想知道在处理响应时是否可以使用组件将响应数据输出到 div?

Just to summarise everything:

简单总结一下:

  1. How do I submit a form using vue js and vue-resource instead of my usual jQuery way?
  2. Using a response from ajax, how can I output data into a div preferably using components?
  1. 如何使用 vue js 和 vue-resource 而不是我通常的 jQuery 方式提交表单?
  2. 使用来自 ajax 的响应,如何最好使用组件将数据输出到 div 中?

Any help on this would be most appreciated, thanks.

对此的任何帮助将不胜感激,谢谢。

回答by scrubmx

I used this approach and worked like a charm:

我使用了这种方法并且工作得很有魅力:

event.preventDefault();

let formData = new FormData(event.target);

formData.forEach((key, value) => console.log(value, key));

回答by Samuel De Backer

  1. Add v-model="id"on your text input

  2. then add it to your data object

    new Vue({
        el: '#someId',
    
        data: {
            id: ''
        },
    
        methods: {
            search: function(e) {
                e.preventDefault();
    
                var req = this.$http.get(
                    '/api/search?id=' + this.id,
                    function (data, status, request) {
                        console.log(data);
                    }
                );
            }
        }
    });
    
  3. It's better to remove v-on="click: search"and add v-on="submit: search"on the form tag.

  4. You should add method="GET"on your form.
  5. Make sure you have #someIdin your html markup.
  1. 添加v-model="id"您的文本输入

  2. 然后将其添加到您的数据对象

    new Vue({
        el: '#someId',
    
        data: {
            id: ''
        },
    
        methods: {
            search: function(e) {
                e.preventDefault();
    
                var req = this.$http.get(
                    '/api/search?id=' + this.id,
                    function (data, status, request) {
                        console.log(data);
                    }
                );
            }
        }
    });
    
  3. 最好删除v-on="click: search"并添加v-on="submit: search"表单标签。

  4. 你应该method="GET"在你的表格上添加。
  5. 确保您#someId的 html 标记中有。

回答by Anish Dcruz

In order to get the value from input you have to use v-model Directive

为了从输入中获取值,您必须使用 v-model 指令

1. Blade View

1. 刀片视图

<div id="app">
<form v-on="submit: search">
    <div class="form-group">
        <input type="text" v-model="id" class="form-control" placeholder="id" required="required">
    </div>

    <input type="submit" class="btn btn-default" value="Search">
</form>
</div>

<script type="text/javascript">

// get route url with blade 
var url = "{{route('formRoute')}}";

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


var app = new Vue({
    el: '#app',
    data: {
        id: '',
        response: null
    },
    methods: {
        search: function(event) {
            event.preventDefault();

            var payload = {id: this.id};

            // send get request
            this.$http.get(url, payload, function (data, status, request) {

            // set data on vm
            this.response = data;

            }).error(function (data, status, request) {
                // handle error
            });
        }
    }
});
</script>

If you want to pass data to component the use 'props' see docs for more info

如果您想将数据传递给组件,请使用“道具”,请参阅文档以获取更多信息

http://vuejs.org/guide/components.html#Passing_Data_with_Props

http://vuejs.org/guide/components.html#Passing_Data_with_Props

If you want use laravel and vuejs together, then checkout

如果你想一起使用laravel和vuejs,那么checkout

https://laracasts.com/series/learning-vuejs

https://laracasts.com/series/learning-vuejs

I hope this is helpful to you!

我希望这对你有帮助!