FormData 获取表单值 发送数据

前言:怎么每天都能遇到这么奇奇怪怪的问题。当有这种想法的时候还是证明自己实力太差了,需要提升的还有很多呀!

事情是这样的 需要做一个的表单提交需求 提交成功与失败都有个提示?心想 这还不简单 把要传递的参数传给后台 然后给我个返回值 我拿着返回值判断不就OK了 想到这样我就开始做了

在这里插入图片描述)

先把大致写出来
在这里插入图片描述
Index


import React from 'react'
import { Form, Input, Button, Select } from 'antd';
const { Option } = Select;
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};



const index = () =>
{
    const validateMessages = {
        required: '${label} is required!',
        types: {
            email: '${label} is not a valid email!',
            number: '${label} is not a valid number!',
        },
        number: {
            range: '${label} must be between ${min} and ${max}',
        },
    };
  const onFinish = (values) =>
    {
        let options = {
            method: 'post',
            body: values.user
        }
        fetch('http://114.255.136.222:7000/red-market/activity/activity_upload', options).then(response =>
        {
            console.log(response, 'response');
        }, error =>
        {
            console.log(error, 'error');
        })
    };
    return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', backgroundColor: 'pink', height: '100vh' }}>

            <Form id='form' style={{ width: "1200px", textAlign: 'center' }} {...layout} name="nest-messages" onFinish={onFinish} validateMessages={validateMessages}>
                <Form.Item name={['user', 'name']} label="名称" rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item name={['user', 'address']} label="地点" rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item
                    name={['user', 'type']}
                    label="类型"
                    hasFeedback
                >
                    <Select >
                        <Option value="羽神">羽神</Option>
                        <Option value="少主">少主</Option>
                    </Select>
                </Form.Item>
                <Form.Item name={['user', 'startTime']} label="开始时间">
                    <Input />
                </Form.Item>
                <Form.Item name={['user', 'endTime']} label="结束时间">
                    <Input />
                </Form.Item>
                <Form.Item name={['user', 'activiTime']} label="活动时间">
                    <Input />
                </Form.Item>
                <Form.Item name={['user', 'introduce']} label="介绍">
                    <Input />
                </Form.Item>
                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                </Form.Item>
            </Form>

        </div>
    )
}
export default index

提交个试试 ~
在这里插入图片描述
?? object 这还不简单 解析一下不就行了 简简单单
在这里插入图片描述
在这里插入图片描述
是解析成功了 为什么会失败呢?参数传递错了? 苦思许久后才从同事那得知 是 options 表单请求 必须要从表单中发送请求
OPTIONS方法是用于请求获得由Request-URI标识的资源在请求/响应的通信过程中可以使用的功能选项。通过这个方法,客户端可以在采取具体资源请求之前,决定对该资源采取何种必要措施,或者了解服务器的性能。

~一条华丽的分割线~~~~~~~~~

抱着这个好奇心去使用form表单去尝试一下
在这里插入图片描述

样式是不是很丑 ~ 凑合看吧


import React from 'react'

const formItem = [
    { name: '名称', genre: 'name' },
    { name: '地点', genre: 'address' },
    { name: '类型', genre: 'type' },
    { name: '开始时间', genre: 'startTime' },
    { name: '结束时间', genre: 'endTime' },
    { name: '活动时间', genre: 'activiTime' },
    { name: '介绍', genre: 'introduce' },
]
const index = () =>
{
    return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
            <form method="post" encType="multipart/form-data" id="frameName" action='接口地址' target="FromIframe">
                {/* <form id='form' target="nm_iframe"> */}
                {formItem.map((data, index) => (

                    <label style={{ display: 'block' }} htmlFor="name"> <span style={{ width: '80px', marginBottom: '10px', display: 'inline-block', textAlign: 'right', marginRight: "10px" }}>{data.name}:</span><input type="text" name={data.genre} id="name" /></label>
                ))}

                <label htmlFor="img"><span style={{ width: '80px', display: 'inline-block', textAlign: 'right', marginRight: "10px" }}>图片:</span><input type="file" name="image" id="img" /> </label>
                <button  >提交</button>
            </form>
            <iframe id="FromIframe" name="FromIframe"  ></iframe>
        </div>
    )
}
export default index

在这里插入图片描述
是请求成功了 ~ 那么怎么获取到他的返回值呢
在这里插入图片描述
嵌套的iframe中有这个字段 再次尝试着拿到里面的DOM
form + iframe 获取表单提交后返回的数据
随后引用了 jquery jquery-form
由于是嵌套的页面 得不到里面的值 出现了跨域问题等等 被迫换种方法
在这里插入图片描述

~一条华丽的分割线~~~~~~~~~~~~~~~~~~~~~~~~

不绕圈子了 ~ 又来新需求了 简而言之吧

在这里插入图片描述

new FormData 获取表单值 打印的话会是FormData 空对象使用的原生 fetch 请求获取表单值 当初使用axios 这样操作是得不到的 应该也有相应Api 没查~

 let formData = new FormData(document.getElementById('form'));
        let options = {
            method: 'post',
            body: formData
        }

获取到表单的 FormData 说到这里就想起了之前使用jQuery提交的时候了 不说了 自己看吧 新需求 新需求

  $('#login_form').on('submit', function (e) {
      e.preventDefault()
      let formData = $(this).serialize()
      console.log(formData)

      $.ajax({
        url: '/login',
        type: 'post',
        data: formData,
        dataType: 'json',
        success: function (data) {
          let err_code = data.err_code
          if (err_code === 0) {
            // window.alert('注册成功')
            window.location.href = '/'
            // 服务端重定向针对异步请求无效
          } else if (err_code === 1) {
            window.alert('邮箱或者密码错误')
          }
          else if (err_code === 500) {
            window.alert('服务器忙,请稍后重试')
          }
        }
      })
    })

index

import React from 'react'
import styles from './style.less'

const index = () =>
{

  const Processing = (e) =>
    {
        e.preventDefault()
        let formData = new FormData(document.getElementById('form'));
        let options = {
            method: 'post',
            body: formData
        }
        fetch('http://114.255.136.222:7000/red-market/activity/activity_upload', options).then(response =>
        {
            console.log(response, 'response');
        }, error =>
        {
            console.log(error, 'error');
        })
    }

    return (
        <div className={styles.container}>

            {/* // 设置id 以便获取表单序列化 */}
            <form id='form' onSubmit={Processing}>
                <h1>您好
                    <span>欢迎来到后陈。</span>
                </h1>

                <label>
                    <span>姓名 :</span>
                    <input id="name" type="text" name="name" placeholder="来将可留姓名" />
                </label>
                <label>
                    <span>地点 :</span>
                    <input id="address" type="text" name="address" placeholder="敢问少侠在哪" />
                </label>
                <label>
                    <span>类型 :</span><select name="type">
                        <option value='羽神'>羽神</option>
                        <option value='少主'>少主</option>
                    </select>
                </label>

                <label>
                    <span>startTime:</span>
                    <input id="startTime" type="text" name="startTime" placeholder="开始时间" />
                </label>
                <label>
                    <span>endTime :</span>
                    <input id="endTime" type="text" name="endTime" placeholder="结束时间" />
                </label>
                <label>
                    <span>ActivityTime :</span>
                    <input id="ActivityTime" type="text" name="activiTime" placeholder="活动时间" />
                </label>
                <label>
                    <span>介绍 :</span>
                    <textarea id="message" name="message" placeholder="好得说几句话吧"></textarea>
                </label>
                <label>
                    <span>图片 :</span>
                    <input id="image" type="file" name="image" />
                </label>

                <label>
                    <div className={styles.submitContainer}>
                        <input type="submit" className={styles.submit} value="提交" />
                    </div>
                </label>
            </form>
        </div>
    );
};

export default index

css


.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #555;
  background-color: pink;
  padding: 20px 30px 20px 30px;
  font: 18px "Helvetica Neue", Helvetica, Arial, sans-serif;
  color: #D3D3D3;
  text-shadow: 1px 1px 1px #444;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
}

h1 {
  padding: 0px 0px 10px 40px;
  display: block;
  border-bottom: 1px solid #444;
  margin: -10px -30px 30px -30px;
}

h1>span {
  display: block;
  font-size: 11px;
}

label {
  display: block;
  margin: 0px 0px 5px;
}

label>span {
  float: left;
  //   width: 20%;
  text-align: right;
  padding-right: 10px;
  margin-top: 10px;
  font-weight: bold;
}

input[type="text"],
input[type="email"],
textarea {
  text-align: center;
  border: none;
  color: #525252;
  height: 25px;
  line-height: 15px;
  margin-bottom: 16px;
  margin-right: 6px;
  margin-top: 2px;
  outline: 0 none;
  width: 100%;
  border-radius: 2px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  background: #DFDFDF;
}

select {
  text-align: center;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  text-indent: 0.01px;
  text-overflow: '';
  width: 70%;
  height: 35px;
  color: #525252;
  line-height: 25px;
}

textarea {
  height: 100px;
  padding-top: 5px;
  width: 70%;
}


.submitContainer {
  display: flex;
  justify-content: center;
  margin-top: 10px;

  .submit {
    background: #FFCC02;
    border: none;
    padding: 10px 25px 10px 25px;
    color: #585858;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    text-shadow: 1px 1px 1px #FFE477;
    font-weight: bold;
    box-shadow: 1px 1px 1px #3D3D3D;
    -webkit-box-shadow: 1px 1px 1px #3D3D3D;
    -moz-box-shadow: 1px 1px 1px #3D3D3D;

    &:hover {
      color: #333;
      background-color: #EBEBEB;
    }
  }
}

修改后的自动填充日期

在这里插入图片描述

修改 formData表单值

修改了 自动填充时间之后 格式对不上 ~ 需要格式:2021年10月10日 格式化日期后的格式:2021-10-10 随后使用了 import Moment from 'moment' 格式化日期
并且修改了原有 formData 的值

        let formData = new FormData(document.getElementById('addBookForm'));
        formData.set('startTime', Moment(formData.get('startTime')).format('YYYY[年]MMMDo'))
        formData.set('endTime', Moment(formData.get('endTime')).format('YYYY[年]MMMDo'))
        formData.set('activiTime', Moment(formData.get('activiTime')).format('YYYY[年]MMMDo'))

formData 追加 key:value 以及 formData.getAll查看

在这里插入图片描述

        formData.append('username', '羽神');
        formData.append('username', '少主');
        formData.getAll('username')  // ["羽神","少主"]
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

臧小川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值