简体   繁体   English

如何将表单数据发布为JSON?

[英]How to post form data as JSON?

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. 我正在尝试为我们正在研究的小组项目建立一个注册站点,但无法弄清楚如何将表单数据作为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: 我的问题是,当我按下“提交”按钮时,我从API收到了这样的错误:

{"":["The input was not valid."]} {“”:[“输入无效。”]}

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. 我认为原因是我的表单未将数据作为JSON发送,而是根据其API文档对它们进行了格式化。 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. 任何帮助将不胜感激,因为我对这样的编码不是很熟悉。

Edit: 编辑:

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);
        }
    })
});
});

I tested it with our teachers test api also and the response is this: 我也用我们的老师测试API测试了它,响应是这样的:

{"message":"Bad Request","reason":"val: nil fails spec: :user-system.spec/login-request predicate: map?\\n"} {“消息”:“错误请求”,“原因”:“ val:无失败规范::user-system.spec / login-request谓词:map?\\ n“}

There's a couple problems here. 这里有几个问题。

  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 ^ 
  2. Selecting register_form instead of #register_form in two places, the second was unnecessary regardless because you could reference this instead. 在两个地方选择register_form而不是#register_form ,第二个不必要,因为您可以引用this This also resulted in the form submission not being cancelled. 这也导致表单提交没有被取消。

  3. You didn't include a $.serializeJSON plugin, again I'm assuming this is a copy and paste error. 您没有包含$.serializeJSON插件,同样,我假设这是复制和粘贴错误。

  4. $.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. $.serializeJSON (无论您选择哪种方式)都应该返回一个JSON字符串,但是您对结果运行JSON.stringify ,这将是字符串中的一个字符串。

  5. 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. https://https://这不是一个大问题,因为它处于不应提交但值得一提的表单的action属性中。

In the example below I've provided a simple replacement for $.serializeJSON , and corrected the rest of the issues listed above. 在下面的示例中,我提供了$.serializeJSON的简单替换,并更正了上面列出的其余问题。 serialize_form in the code below can be replaced with whatever $.serializeJSON plugin you choose to use. 下面代码中的serialize_form可以替换$.serializeJSON您选择使用的$.serializeJSON插件。

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. 我已经注释掉了ajax请求,因为这里真正要关注的是从表单数据中获取JSON,因此我只是将其登录到控制台,以便您可以看到它是JSON字符串。 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> 

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

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

    var obj = $('#registerForm').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>

try this 尝试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM