如何将HTML表单数据作为JSON发送到服务器?

时间:2021-09-30 07:08:52

First of all i know plenty of questions out there with the same Title.. I saw so many things, but nothing works so far for me. Thats why i opened this Question.

首先,我知道很多问题都有相同的标题..我看到了很多东西,但到目前为止我没有任何作用。这就是为什么我打开这个问题。

i have TWO scenarios basically 1) defining "action" and "method" in html form. 2) without "action" and "method" in html form.

我有两个场景基本上1)用html格式定义“动作”和“方法”。 2)没有html形式的“动作”和“方法”。

So here is the FIRST scenario,

所以这是第一种情况,

1) I have a form with just two fields namely email and password.

1)我有一个只有两个字段的表单,即电子邮件和密码。

here is the snippit

这是snippit

<form id="login-form" action="http://192.168.52.166:6000/api/2/users/login/" method="post">

<p><label for="email">Email</label>
<input type="email" name="email" id="email"></p>

<p><label for="password">Password</label>
<input type="password" name="password" id="password"></p>

<button value="Submit" type="submit">Login</button>
</form>

First when i submit form, it send all my field values as url encoded. the default content-type of a form is urlencoded. i know that. So now what i did is, added ajax to send it as json.

首先,当我提交表单时,它会将所有字段值发送为url编码。 urlencoded表单的默认内容类型。我知道。所以现在我做的是,添加ajax将其作为json发送。

here is my jquery snippit,

这是我的jquery snippit,

$('form').submit(function(){

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

    $.ajax({
        type: 'POST',
        url: 'http://192.168.52.166:6000/api/2/users/login/',
        dataType: 'json',
        data: JSON.stringify(obj),
        contentType : 'application/json',
        success: function(data) {
            alert(data)
        }
    });

i am using SerializeJSON library to serealize the form data to json.

我正在使用SerializeJSON库将表单数据实现到json。

now what happens is the same thing, it sends the form data as urlencoded while it suppose to send as json to server.

现在发生的事情是一样的,它将表单数据发送为urlencoded,而它假设将json作为服务器发送。

after the serializeJSON(); function when i alert the data, it successfully shows as json.

在serializeJSON()之后;当我提醒数据时,它成功显示为json。

here is what i did

这就是我做的

var obj = $('form').serializeJSON();
var jsonString = JSON.stringfy(obj);
alert(jsonString)

it successfully alerts me with json value of my form fields. but when i use it with ajax jquery as shown in above jquery form demo, that json string suppose to travels to server. but it is not, instead it goes as like urlencoded.

它成功提醒我我的表单字段的json值。但是当我将它与ajax jquery一起使用时,如上面的jquery表单演示所示,那个json字符串假设要转到服务器。但它不是,而是像urlencoded一样。

2) SECOND scenario is same as FIRST one, but this time without form's action and method. What is happening now is my form method acts as GET even though i mentioned POST in jquery.

2)SECOND场景与第一场景相同,但这次没有形式的动作和方法。现在发生的事情是我的表单方法充当GET,即使我在jquery中提到了POST。

Note: I checked all the reports with Wireshark to check for HTTP request and Response.

注意:我使用Wireshark检查了所有报告,以检查HTTP请求和响应。

What am i doing wrong in here? I just want to send JSON data to server instead of URLEncoded. What i should i do?

我在这里做错了什么?我只想将JSON数据发送到服务器而不是URLEncoded。我该怎么办?

Edit: i found out another thing. When i send form data without defining action and method in html form, i recive following request and response from server. (these responses are taken from Wireshark)

编辑:我发现了另一件事。当我发送表单数据而没有以html格式定义动作和方法时,我会从服务器返回以下请求和响应。 (这些回复来自Wireshark)

OPTIONS /api/2/users/login/ HTTP/1.1
Host: 192.168.52.166:6000
Access-Control-Request-Method: POST
Origin: http://localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost/app/login.html
Accept-Language: en-US,en;q=0.8,ca;q=0.6
Accept-Encoding: gzip

HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 14 Nov 2016 00:55:42 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Allow: POST, OPTIONS

so it seems like when i mention POST in jquery instead of in html form. it is not working.

所以当我在jquery而不是html形式中提到POST时。它不起作用。

Here is what i get when i use action and method in html form.

这是我在html表单中使用动作和方法时得到的结果。

POST /api/2/users/login/ HTTP/1.1
Host: 192.168.52.166:6000
Content-Length: 48
Cache-Control: max-age=0
Origin: http://localhost
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://localhost/app/login.html
Accept-Language: en-US,en;q=0.8,ca;q=0.6
Cookie: csrftoken=M5ItY7prMtJLBZWOJAN4D9uMDs2uFz5d
Accept-Encoding: gzip

email=emjimadhu%40email.com&password=qwerty123

HTTP/1.1 201 CREATED
Server: nginx/1.4.6 (Ubuntu)
Date: Sun, 13 Nov 2016 18:11:51 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Allow: POST, OPTIONS
Set-Cookie: csrftoken=tFSyA9OSfyBi4NHoU6FVFSD7BZOE6S1a; expires=Sun, 12-Nov-2017 18:11:51 GMT; Max-Age=31449600; Path=/
Set-Cookie: sessionid=eoaq13tgrjdmsqwcke7zbhgv92dec9c3; expires=Sun, 27-Nov-2016 18:11:51 GMT; httponly; Max-Age=1209600; Path=/

Answer Found

找到答案

First of all thank you all who tried to answer.. None of the answer worked for me.. It's cause there wasn't a coding problem.. I read jquery Ajax as API and found out, defining other than URL encode in contentType will trigger OPTIONS flag instead of POST.. Basically what it does is browser will send a pre request with OPTIONS flag and based on servers HTTP status, it will send real request.. It's happening cause my back end server doesn't allow cross origin request.. That's why I got those problems.. I found a chrome extension which allows cross origin temporarily.. That cleared my problem..

首先,谢谢所有试图回答的人..没有一个答案对我有用..这是因为没有编码问题..我读了jquery Ajax作为API并发现,在contentType中定义除了URL编码之外触发OPTIONS标志而不是POST ..它的作用基本上是浏览器将发送带有OPTIONS标志的预请求并基于服务器HTTP状态,它将发送实际请求..这是因为我的后端服务器不允许交叉来源请求..这就是我遇到这些问题的原因..我发现了一个镀铬扩展,允许暂时交叉原点..这清除了我的问题..

Here is the link to that chrome extension

这是Chrome扩展程序的链接

Link to chrome extension

链接到chrome扩展程序

It is highly not appropriate solution.. But if you have same situation as mine, you can use it..

这是非常不合适的解决方案..但如果你和我的情况相同,你可以使用它..

My situation is I developed front end and having API to making request.. But my back end, I didn't developed it.. So the source is far away.. While in production environment, all my files will be merged in server.. But for now, for testing, I needed to use this extension to work with my API..

我的情况是我开发了前端并且有API来提出请求..但是我的后端,我没有开发它..所以源远远...在生产环境中,我的所有文件将合并到服务器中。但是现在,为了测试,我需要使用这个扩展来使用我的API ..

6 个解决方案

#1


0  

You have to change the function as event-listener.

您必须将该功能更改为事件侦听器。

    $('#form').on('submit', function(event){

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

        $.ajax({
            type: 'POST',
            url: 'http://192.168.52.166:6000/api/2/users/login/',
            dataType: 'json',
            data: JSON.stringify(obj),
            contentType : 'application/json',
            success: function(data) {
                alert(data)
            }
        });

       return false;
   });

#2


0  

Don't submit the form and then make an Ajax request. Make the form button not of submit type, just call Ajax from it's onclick.

不要提交表单然后发出Ajax请求。使表单按钮不是提交类型,只需从它的onclick调用Ajax。

Or, if you want to work less, just change the form action to some idle value "javascript://", so that only the ajax request is actually sent to the server on the submit event:

或者,如果您想减少工作量,只需将表单操作更改为某个空闲值“javascript://”,这样只有ajax请求实际上会在提交事件上发送到服务器:

<form id="login-form" action="javascript://" method="post">

#3


0  

$('#form').on('submit', function(event){

        var obj = $('form').serialize();

        $.ajax({
            type: 'POST',
            url: 'http://192.168.52.166:6000/api/2/users/login/',
            dataType: 'json',
            data: obj,
            contentType : 'application/json',
            success: function(data) {
                alert(data)
            }
        });

       return false;
   });

#4


0  

here is my code It will help you:

这是我的代码它会帮助你:

  <form name="myform" id="myform">
    <div class="form-group">
      <label for="fullName">Name:</label>
      <input type="text" name="fullName" class="form-control">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" name="email" class="form-control">
    </div>
    <div class="form-group">
      <label for="subject">Subject:</label>
      <input type="text" name="subject" class="form-control">
    </div>
    <div class="form-group">
      <label for="mark">Mark:</label>
      <input type="number" name="mark" class="form-control">
  </form>
  <button type="submit" class="btn btn-success " id="submitform">Submit</button>


  <script>
  $(document).ready(function () {
      $("#submitform").click(function (e) {
          var MyForm = JSON.stringify($("#myform").serializeJSON());
          console.log(MyForm);
          $.ajax(
              {
                  url: "<your url>",
                  type: "POST",
                  data: MyForm,
              });
          e.preventDefault(); //STOP default action
      });
  });
  </script>

#5


-1  

You can't use the http protocol within a post or get request, you must place the path of your file within your directories on your server, without making external requests, try removing http://192.168.52.166:6000/ from your request POST

您不能在帖子或获取请求中使用http协议,您必须将文件的路径放在服务器上的目录中,而无需提出外部请求,请尝试从您的请求中删除http://192.168.52.166:6000/ POST

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

#6


-2  

try this remove JSON.stringify() from data. $.ajax({ type: 'POST', url: 'http://192.168.52.166:6000/api/2/users/login/', dataType: 'json', data: obj, contentType : 'application/json', success: function(data) { alert(data) } });

尝试从数据中删除JSON.stringify()。 $ .ajax({type:'POST',url:'http://192.168.52.166:6000 / api / 2 / users / login /',dataType:'json',data:obj,contentType:'application / json ',success:function(data){alert(data)}});

#1


0  

You have to change the function as event-listener.

您必须将该功能更改为事件侦听器。

    $('#form').on('submit', function(event){

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

        $.ajax({
            type: 'POST',
            url: 'http://192.168.52.166:6000/api/2/users/login/',
            dataType: 'json',
            data: JSON.stringify(obj),
            contentType : 'application/json',
            success: function(data) {
                alert(data)
            }
        });

       return false;
   });

#2


0  

Don't submit the form and then make an Ajax request. Make the form button not of submit type, just call Ajax from it's onclick.

不要提交表单然后发出Ajax请求。使表单按钮不是提交类型,只需从它的onclick调用Ajax。

Or, if you want to work less, just change the form action to some idle value "javascript://", so that only the ajax request is actually sent to the server on the submit event:

或者,如果您想减少工作量,只需将表单操作更改为某个空闲值“javascript://”,这样只有ajax请求实际上会在提交事件上发送到服务器:

<form id="login-form" action="javascript://" method="post">

#3


0  

$('#form').on('submit', function(event){

        var obj = $('form').serialize();

        $.ajax({
            type: 'POST',
            url: 'http://192.168.52.166:6000/api/2/users/login/',
            dataType: 'json',
            data: obj,
            contentType : 'application/json',
            success: function(data) {
                alert(data)
            }
        });

       return false;
   });

#4


0  

here is my code It will help you:

这是我的代码它会帮助你:

  <form name="myform" id="myform">
    <div class="form-group">
      <label for="fullName">Name:</label>
      <input type="text" name="fullName" class="form-control">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" name="email" class="form-control">
    </div>
    <div class="form-group">
      <label for="subject">Subject:</label>
      <input type="text" name="subject" class="form-control">
    </div>
    <div class="form-group">
      <label for="mark">Mark:</label>
      <input type="number" name="mark" class="form-control">
  </form>
  <button type="submit" class="btn btn-success " id="submitform">Submit</button>


  <script>
  $(document).ready(function () {
      $("#submitform").click(function (e) {
          var MyForm = JSON.stringify($("#myform").serializeJSON());
          console.log(MyForm);
          $.ajax(
              {
                  url: "<your url>",
                  type: "POST",
                  data: MyForm,
              });
          e.preventDefault(); //STOP default action
      });
  });
  </script>

#5


-1  

You can't use the http protocol within a post or get request, you must place the path of your file within your directories on your server, without making external requests, try removing http://192.168.52.166:6000/ from your request POST

您不能在帖子或获取请求中使用http协议,您必须将文件的路径放在服务器上的目录中,而无需提出外部请求,请尝试从您的请求中删除http://192.168.52.166:6000/ POST

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

#6


-2  

try this remove JSON.stringify() from data. $.ajax({ type: 'POST', url: 'http://192.168.52.166:6000/api/2/users/login/', dataType: 'json', data: obj, contentType : 'application/json', success: function(data) { alert(data) } });

尝试从数据中删除JSON.stringify()。 $ .ajax({type:'POST',url:'http://192.168.52.166:6000 / api / 2 / users / login /',dataType:'json',data:obj,contentType:'application / json ',success:function(data){alert(data)}});