微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过 vue js 中的 http 帖子发送表单

如何解决如何通过 vue js 中的 http 帖子发送表单

昨天这段代码正在运行,今天显示

v-on 处理程序中的错误:“类型错误:无法读取属性 'get' 未定义"

我能够在没有 axios 的情况下发送 http get。这是我的 vue 代码

<template>
  <div>

    <form id="loginForm">
      <input type="text" name="name" v-model="user.name" />
      <input type="text" name="email" v-model="user.email" />
      <input type="text" name="message" v-model="user.message" />
      <button @click="save">send</button>
    </form>
  </div>
</template>

<script>


export default {
  name: "Contact",components: {
    
  },data() {
    return {
      user: {
        name: "peter",email: "foo@example.com",message: "bla bla bla",},};
  },methods: {
    save: function () {
      let formData = new FormData(document.getElementById("loginForm"));
      this.$http
        .get("http://link.cursolinux.pt:8080/contacts",formData)
        .then((response) => {
          console.log(response.body);
        });
    },};
</script>

对于我的获取请求,我使用的是 laravel 8

Route::get('/contacts',function (Request $request) {
   //get the request
   $post = $request->all();
   
   //show the get request 
   //return response()->json($post);
    
   //storage in database
    \App\Models\Contact::create($post);

});

解决方法

您可能想要 POST 数据而不是使用 GET。

如果您确实需要 GET,则需要将 FormData 对象传递给 URLSearchParams() 以转换为查询字符串

const form = document.querySelector('#loginForm'),fData = new FormData(form),url = new URL(form.action);

url.search = new URLSearchParams(fData);

console.log(url)
<form id="loginForm" action="https://example.com">
  <input name="name" value="foo">
  <input name="age" value="28" />

</form>

,

首先我安装 vue-resource:

npm install vue-resource

然后在文件 main.js 中导入 vue-resource

import Vue from 'vue'
import App from './App.vue'
import VueResource from 'vue-resource'

Vue.use(VueResource);

Vue.config.productionTip = false

new Vue({
  render: h => h(App),}).$mount('#app')

这是我的方法:

  methods: {
    save: function () {
      this.$http
        .get(
          "http://www.url.domain/contacts?name=" +
            this.user.name +
            "&email=" +
            this.user.email
        )
        .then((response) => {
          console.log(response.body);
        });
    },},

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。