简体   繁体   中英

Formulate JSON in JavaScript from HTML form textarea values and Post?

I want to have an HTML form that posts the following in an Http-request body.

{ “info” : {
     “id” : “123”
     “text1” : <comes from html text-box>
}

So, what I want is to formulate the above as a JavaScript Object, and then post this JavaScript object on submit. The value of “text1” will be coming from user input, that will be an html-form textarea input box. The first value “id” will be hard-coded, or could also come from a hidden text-box.

So my question is: how can I write a piece of JavaScript to achieve this, together with the corresponding html form, etc.

<html>
 <head>
  <script>
   function sendJson()
   {
   var x=document.forms["alfa"]["text1"].value;
   str1="{ 'info' : { 'id' : '123' 'text1' : ";
   str2=str1.concat(x);
   body=str2.concat(" }");
   document.forms["alfa"]["text1"].value=body;
   }
  </script>
 </head>
 <body>
  <form id="alfa" onsubmit="return sendJson()">
   Text1: <input id="text1" type=text size=50>
   <input type="submit" value="Submit">
  </form>
 </body>
</html>

It is easiest to do this using jQuery.

First, initialize a JavaScript object with your data. Then, use jQuery to extract the text from the text box and assign it to the desired property in your object.

var data = { 
    "info": {
        "id":"123",
        "text1":"" 
    }
};

data.info.text1 = $("#yourTextBox").val();

Then you can use jQuery.ajax to make the request:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

See the jQuery documentation for posts: http://api.jquery.com/jQuery.post/

EDIT: Using inline javascript, your HTML would look something like this (not using jQuery to grab the form data):

<html>
<head>
<script>
var data = { 
    "info": {
        "id":"123",
        "text1":"" 
    }
};
function makeRequest()
{
    data.info.text1 = document.forms["frm1"]["fname"].value;

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: success,
        dataType: dataType
    });
}
</script>
</head>
<body>

<form name="frm1" id="yourTextBox" onsubmit="makeRequest()">
<input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

最好的方法是使用JSON.parse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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