Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

How to send a JavaScript object along with an html form?

I have an HTML form, which has quite a few input fields. As the user types in one of them, JavaScript generates a few objects that contain data I need to get to the server. I know I can send these objects with AJAX, but I need them to end up in the same function as the normal data from the form once they get server-side (I'm using flask for the backend). Is there any way I can send the objects along with the form, so that they somehow end up in the same place?

Here is the beginning of the form:

<form action="/org/new-task" method="post">
    <div class="mb-3">
        <select name="rep-type" class="form-select">
            <option selected disabled>Type of task</option>
            <option value="0">Ongoing/repeating</option>
            <option value="1">One-off</option>
        </select>
    </div>
    ...

and here is the output when I console.log() one of the objects (there are multiple, but they are very similar):

(2)?["painting", "cleaning"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To have some objects sent with a "normal" form submit... You could store those in some hidden input elements as string.

You will have to parse that string on the python side. Look here for how

let some_object = {
  name: "John",
  last: "Doh"
}

// Stringify the object and store it in the hidden input
let hidden_input = document.querySelector("[name='js_object']")
hidden_input.value = JSON.stringify(some_object)

// Just for this demo... to console log something.
document.querySelector("form").addEventListener("submit", function(e){
  e.preventDefault()
  console.log(hidden_input.value)
  console.log(typeof(hidden_input.value))
})
<form>
  <input type="hidden" name="js_object">
  <button type="submit">Submit</button>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...