gpt4 book ai didi

javascript - form.serializeArray() 的自定义键

转载 作者:行者123 更新时间:2023-12-03 02:49:01 26 4
gpt4 key购买 nike

我有一个通过后端动态创建的调查问卷页面。我需要序列化表单数据,但 form.serialize 数组采用 name 属性,我想为我发送的数据分配自己的 key 。我对 JavaScript 很陌生。我需要将问题 data-id 代替 key 和所选的输入值这可能吗?我正在使用 AJAX 来发布表单。后端是Flask。

The html page

<h4 class="text-edit" id="question-{{key}}" data-id="{{key}} //will be numeric">1. Does the lecturer Communicate clearly?</h4>
<!-- I need the data-id of the h4 tag-->

<input type="radio" name="options1" id="options" value="1" >
<!-- And the value of the value in the radio button-->
<label class="radio-inline mg" for='options'> Yes</label>
<input type="radio" name="options1" id="options" value="2">
<label class="radio-inline mg" for='options'> No</label>

The Javascript I'm using

var dataset = {
"stream": $("#stream_id").data("name"),
"subject": $('#subject_select option:selected').val(),
"teacher": $('#teacher_select option:selected').val()
};
// IF I COULD Even append the data to the above thing that also would work
$.ajax({
url: "{{url_for('question.gen_teacher')}}",
data: $('form#questionform').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

最佳答案

1。使用 .serialize()

实际上,.serialize()方法将使您的表单键的值类似于:

key1=value1&key2=value2

所以只需将一些字符串附加到您的 .serialize() 方法中即可:

var dataset = {
"stream": $("#stream_id").data("name"),
"subject": $('#subject_select option:selected').val(),
"teacher": $('#teacher_select option:selected').val()
};

$.ajax({
url: "{{url_for('question.gen_teacher')}}",
data: $('form#questionform').serialize() + "&data-id=value",
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

2。使用 .serializeArray()

var formData = $('form#questionform').serializeArray();
formData.push({ name: "data-id", value: "somevalue" });

并将 formData 变量放入 $ajax data

请求答案?

HTML:

<h4 h-id="1" class="text-edit" id="question-{{key}}" data-id="{{key}} //will be numeric">1. Does the lecturer Communicate clearly?</h4>

<select answer-id="1">
<option value="1">Yes</option>
<option value="0">No</option>
</select>

JavaScript:

var formData = {};
$("h4[h-id]").each(function(){
var hid = $(this).attr("h-id");
var id = $(this).attr("id");
var answer = $('select[answer-id="'+hid+'"]');
formData.push({id:answer});
})

// ... ajax
data: formData,

关于javascript - form.serializeArray() 的自定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com