- excel apps
- conversion
- json to html
Đánh dấu ứng dụng này
Nhấn Ctrl + D để thêm trang này vào mục yêu thích của bạn hoặc Esc để hủy hành động.
Gửi liên kết tải xuống tới
Gửi cho chúng tôi phản hồi của bạn
Ối! Một lỗi đã xảy ra.
Tệp không hợp lệ, vui lòng đảm bảo rằng tải lên đúng tệpLỗi đã được báo cáo thành công.
Bạn đã thông báo lỗi thành công, Bạn sẽ nhận được email thông báo khi lỗi được khắc phục. Nhấp vào liên kết này để truy cập diễn đàn.
Xóa ngay các tệp đã tải lên và đã xử lý.
Bạn có chắc chắn xóa các tệp không?
Nhập Url
Shahpar Khan
JSON
JSONJavaScript Object Notation is a lightweight, text-based data-interchange format. JSON is based on two basic data structures [ key-value pairs and ordered lists ] and is language-independent. In JSON, data can only be in text form while it is exchanged between a browser and a server. Any JavaScript object can be converted into JSON text.
HTML
HTMLHypertext Markup Language is a language used to design and display web pages. HTML is a formatting language that focuses mainly on its tags and attributes to markup webpages. HTML cannot be referred to as a programming language as it does not contain any conditional statements or dynamic structure.
Methods to convert JSON to HTML
- Use an online convertor
- Use JSON functions
How to use an online convertor
Using an online converter to convert JSON to HTML is a bit tedious and it might not be resorted to dynamic conversion over a website. However, this tool will come in handy if you want to parse one JSON file for reasons not concerning a particular website. Here is a link to an online converter called ConvertJSON. It looks something like this:
ConvertJSON is pretty straightforward. There are three ways you can give your input:
- A JSON file
- A URL
- Raw JSON text
After giving input, you will receive an HTML text that will convert your JSON into an HTML table. You can copy that and use it!
How to use JSON functions
JSON functions are a more useable method and can be easily incorporated into a web application. The key
function that enables us to convert JSON to HTML at runtime is JSON.parse[]
. The JSON.parse[]
method takes textual JSON data and converts it to a JavaScript object. You can then easily use this object to display data in HTML. Let’s look at an example:
Here we have an object with three attributes:
var my_obj = {name: "Erik", age: 17, school: "Edpresso High"};
In the code above, we first created an object and then converted it to JSON using JSON.stringify[]
. This is a good way to mimic the
conversion because the data is received in textual form over the network:
var my_json = JSON.stringify[my_obj];
We then pass this text to the JSON.parse[]
function and it converts it into a JavaScript object:
var my_json = JSON.stringify[my_obj];
var parsed_obj = JSON.parse[my_json];
Finally, we use the object to render the HTML tag:
json_to_html_tag.innerHTML = "Converting JSON to HTML
" +
"Name: " + parsed_obj.name +
"
Age: " + parsed_obj.age +
"
School: " + parsed_obj.school;
CONTRIBUTOR
Shahpar Khan
Copyright ©2022 Educative, Inc. All rights reserved
So I've got this HTML form:
test
First Name:
Last Name:
Which would be the easiest way to send this form's data as a JSON object to my server when a user clicks on submit?
UPDATE: I've gone as far as this but it doesn't seem to work:
function submitform[]{
alert["Sending Json"];
var xhr = new XMLHttpRequest[];
xhr.open[form.method, form.action, true];
xhr.setRequestHeader['Content-Type', 'application/json; charset=UTF-8'];
var j = {
"first_name":"binchen",
"last_name":"heris",
};
xhr.send[JSON.stringify[j]];
What am I doing wrong?
asked Mar 5, 2014 at 10:29
10
Get complete form data as array and json stringify it.
var formData = JSON.stringify[$["#myForm"].serializeArray[]];
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it. You'll then get all data in an array.
$.ajax[{
type: "POST",
url: "serverUrl",
data: formData,
success: function[]{},
dataType: "json",
contentType : "application/json"
}];
answered Mar 5, 2014 at 10:35
SachinGutteSachinGutte
6,7575 gold badges34 silver badges58 bronze badges
1
HTML provides no way to generate JSON from form data.
If you really want to handle it from the client, then you would have to resort to using JavaScript to:
- gather your data from the form via DOM
- organise it in an object or array
- generate JSON with JSON.stringify
- POST it with XMLHttpRequest
You'd
probably be better off sticking to application/x-www-form-urlencoded
data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.
Update in response to major rewrite of the question…
- Your JS has no
readystatechange
handler, so you do nothing with the response - You trigger the JS when the submit button is clicked without cancelling the default behaviour. The browser will submit the form [in the regular way] as soon as the JS function is complete.
answered Mar 5, 2014 at 10:33
QuentinQuentin
872k121 gold badges1170 silver badges1284 bronze badges
12
You can try something like:
test
Encode
encode. title = async [e] => {
let response = await fetch['//localhost:8482/encode', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}]
let text = await response.text[]; // read response body as text
data = JSON.parse[text];
document.querySelector["#encoded"].innerHTML = text;
// document.querySelector["#encoded"].innerHTML = `First name = ${data.firstname}
// Last name = ${data.lastname}
// Age = ${data.age}`
};
formElem.onsubmit = async [e] => {
e.preventDefault[];
var form = document.querySelector["#formElem"];
// var form = document.forms[0];
data = {
firstname : form.querySelector['input[name="firstname"]'].value,
lastname : form.querySelector['input[name="lastname"]'].value,
age : 5
}
let response = await fetch['//localhost:8482/decode', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify[data],
}]
let text = await response.text[]; // read response body as text
document.querySelector["#decoded"].innerHTML = text;
};
answered Aug 4, 2020 at 21:15
Hasan A YousefHasan A Yousef
20.3k22 gold badges118 silver badges177 bronze badges
I'm late but I need to say for those who need an object, using only html, there's a way. In some server side frameworks like PHP you can write the follow code:
First Name:
Last Name:
So, we need setup the name of the input as object[property]
for got an object. In the above example, we got a data with the follow JSON:
{
"name": {
"first": "some data",
"last": "some data"
}
}
answered Mar 3, 2020 at 2:31
orafaelreisorafaelreis
2,7592 gold badges27 silver badges31 bronze badges
2
you code is fine but never executed, cause of submit button [type="submit"] just replace it by type=button
inside your script; form is not declared.
let form = document.forms[0];
xhr.open[form.method, form.action, true];
answered Apr 5, 2019 at 2:57
tdjprogtdjprog
6886 silver badges11 bronze badges
1
Use FormData API
- Capture the form data using FormData API
formData= new FormData[form]
- Convert it
into JSON using
JSON.stringify[Object.fromEntries[formData]]
- Send this strigified json as ajax payload
var form = document.getElementById['myForm'];
form.onsubmit = function[event]{
var xhr = new XMLHttpRequest[];
var formData = new FormData[form];
//open the request
xhr.open['POST','//localhost:7000/tests/v1.0/form']
xhr.setRequestHeader["Content-Type", "application/json"];
//send the form data
xhr.send[JSON.stringify[Object.fromEntries[formData]]];
xhr.onreadystatechange = function[] {
if [xhr.readyState == XMLHttpRequest.DONE] {
form.reset[]; //reset form after AJAX success or do something else
}
}
//Fail the onsubmit to avoid page refresh.
return false;
}
Taken from an article I wrote here: //metamug.com/article/html5/ajax-form-submit.html
Samuel Liew♦
73.6k106 gold badges156 silver badges238 bronze badges
answered Sep 29, 2021 at 10:15
SorterSorter
9,0865 gold badges59 silver badges71 bronze badges
If you want to use pure javascript in 2022...
const ajax = async [config] => {
const request = await fetch[config.url, {
method: config.method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify[config.payload]
}];
response = await request.json[];
console.log['response', response]
return response
}
// usage
response = ajax[{
method: 'POST',
url: 'example.com',
payload: {"name": "Stackoverflow"}
}]
answered Aug 30 at 10:04
The micro-library
field-assist does exactly that: collectValues[formElement]
will return a normalized json from the input fields [that means, also, checkboxes as booleans, selects as strings,etc].
answered Dec 8, 2020 at 16:30
Avi TshuvaAvi Tshuva
2482 silver badges12 bronze badges
I found a way to pass a JSON message using only a HTML form.
This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.
GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.
{
allUsers
{
userId
}
}
I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.
In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.
answered Nov 20, 2020 at 0:02
IsraelmIsraelm
1,5773 gold badges20 silver badges28 bronze badges
1