如何将表单数据发布为JSON? [英] How to post form data as JSON?

查看:58
本文介绍了如何将表单数据发布为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我们正在从事的小组项目建立一个注册站点,但无法弄清楚如何将表单数据作为json发送.我尝试了很多谷歌搜索和更改代码,但似乎没有任何效果.我遇到的问题是,当我按下提交"按钮时,我从API中收到了这样的错误:

I'm trying to build a registration site for a group project we are working on but can't figure out how to send the form data as json. I've tried googling a lot and changing the code but nothing seems to work. The problem I have is that when i press on the submit button I get an error like this from the API:

{":[输入无效."]}

{"":["The input was not valid."]}

我认为原因是我的表单未将数据作为JSON发送,而是根据其API文档格式化它们所需的格式.我的表单代码如下:

I think the reason is that my form does not send the data as JSON and it's they format they require according to their API documentation. My form code looks like this:

<form id="register_form" action="https://https://url.com/users/register" method="post">
        <input type="text" pattern="[A-Za-z]{1,20}" placeholder="Name" name="name" title="Up to 20 alphabetical characters" required>
        <input type="email" placeholder="Email" name="email" title="Must be a valid email address" required>
        <input type="password" pattern="[a-zA-Z0-9-]+{8,20}" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
        <input type="text" pattern="[a-zA-Z0-9-]+" placeholder="Homeadress" name="homeadress">
        <input type="text" placeholder="Postnumber" name="postnumber">
        <input type="text" placeholder="City" name="city">
        <br>
        <button value="Submit" type="submit">Register</button>
</form>

我一直试图开始工作的脚本如下:

And the script i've been trying to get to work looks like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>

<script type="text/javascript">
  $('register_form').on('submit', function(event){

    var obj = $('register_form').serializeJSON();

    $.ajax({
        type: 'POST',
        url: 'https://url.com/users/register',
        dataType: 'json',
        data: JSON.stringify(obj),
        contentType : 'application/json',
        success: function(data) {
            alert(data)
        }
    });

   return false;
 });
</script>

由于我对这样的编码不是很熟悉,所以任何帮助将不胜感激.

Any help would be greatly appreciated since I'm not very familiar with coding stuff like this.

我也使用这样的脚本进行了尝试,但仍然得到了相同的响应:

I also tried it with a script like this but still getting the same response:

<script>

$(document).ready(function(){

    $("#submit").on('click', function(){

   var formData = {

        "name": $('input[name=name]').val(),
        "email": $('input[name=email]').val(),
        "password": $('input[name=password]').val(),
        "homeadress": $('input[name=homeadress]').val(),
        "postnumber": $('input[name=postnumber]').val(),
        "city": $('input[name=city]').val()
    };

       $.ajax({
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        url: 'https://url.com/users/register', 
        type : "POST", 
        dataType : 'json', 
        data : JSON.stringify(formData), 
        success : function(result) {

            console.log(result);
        },
        error: function(xhr, resp, text) {
            console.log(xhr, resp, text);
        }
    })
});
});

我也用我们的教师测试api测试了它,响应是这样的:

I tested it with our teachers test api also and the response is this:

{消息":错误请求",原因":"val:无失败规范::user-system.spec/login-request谓词:map?\ n}

{"message":"Bad Request","reason":"val: nil fails spec: :user-system.spec/login-request predicate: map?\n"}

推荐答案

这里有几个问题.

  1. 脚本元素的无效开始标记.这可能是复制和粘贴错误,但值得一提:

  1. Invalid start tag for script element. This was probably a copy and paste error, but worth mentioning:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
                                                 missing greater than symbol ^

  • 在两个位置选择register_form而不是#register_form,第二个位置是不必要的,因为您可以引用this.这也导致表单提交没有被取消.

  • Selecting register_form instead of #register_form in two places, the second was unnecessary regardless because you could reference this instead. This also resulted in the form submission not being cancelled.

    您没有包含$.serializeJSON插件,我再次假设这是复制和粘贴错误.

    You didn't include a $.serializeJSON plugin, again I'm assuming this is a copy and paste error.

    $.serializeJSON(无论您选择哪种方式)都应返回JSON字符串,但是您对结果运行JSON.stringify,该结果将是字符串中的一个字符串.

    $.serializeJSON (whichever you choose) should return a JSON string, but you run JSON.stringify on the result, which will be a string inside a string.

    https://https://这不是一个大问题,因为它位于不应提交但值得一提的表单的action属性中.

    https://https:// This isn't a huge issue because it is in the action attribute of a form that should never submit, but worth mentioning.

    在下面的示例中,我提供了对$.serializeJSON的简单替换,并更正了上面列出的其余问题.可以将以下代码中的serialize_form替换为您选择使用的任何$.serializeJSON插件.

    In the example below I've provided a simple replacement for $.serializeJSON, and corrected the rest of the issues listed above. serialize_form in the code below can be replaced with whatever $.serializeJSON plugin you choose to use.

    我已经注释掉了ajax请求,因为这里真正要关注的是从表单数据中获取JSON,因此我只是将其登录到控制台,以便您可以看到它是JSON字符串.我还从输入中删除了模式属性和必需的标志,以便于测试.

    I have commented out the ajax request as what is really of concern here is getting the JSON from the form data, so I just log it to the console instead so that you can see it is a JSON string. I also removed the pattern attributes and required flags from the input for ease of testing.

    const serialize_form = form => JSON.stringify(
      Array.from(new FormData(form).entries())
           .reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
    );
    
    $('#register_form').on('submit', function(event) {
      event.preventDefault();
      const json = serialize_form(this);
      console.log(json);
      /*$.ajax({
        type: 'POST',
        url: 'https://url.com/users/register',
        dataType: 'json',
        data: json,
        contentType: 'application/json',
        success: function(data) {
          alert(data)
        }
      });*/
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="register_form" action="https://url.com/users/register" method="post">
      <input type="text" placeholder="Name" name="name" title="Up to 20 alphabetical characters">
      <input type="email" placeholder="Email" name="email" title="Must be a valid email address">
      <input type="password" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter">
      <input type="text" placeholder="Homeadress" name="homeadress">
      <input type="text" placeholder="Postnumber" name="postnumber">
      <input type="text" placeholder="City" name="city">
      <br>
      <button value="Submit" type="submit">Register</button>
    </form>

    这篇关于如何将表单数据发布为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆