Javascript 未定义数据:无法将表单数据发布到 db 中



我正在构建一个HTML表单,可以连接到php api,以便获得客户端数据,然后将其放入mysql数据库,以便我可以更新用户统计。

现在我正在将数据转换为JSON对象,然后我使用JSON。stringify创建一个字符串,以便将该字符串值发送到HTTP请求中。

$(document).ready(function() {
// (*1*) show (filled out) html form when the user clicks on the 'update product' button
$(document).on('click', '.aggiorna_persona_button', function(e) { // first par = event; second (optional) par = selector (in this case the class); last par = event handler
e.preventDefault();
// get product id
const giorni = $(this).attr('data-id'); // this = clicked button; read the value of data-id attribute
sendRequest("leggi_uno.php?giorno=" + giorni, data => {
let
aggiorna_persona_html = indietro_button();
aggiorna_persona_html += `
<!-- build 'update product' html form -->
<form id='aggiorna_persona_form'name="aggiorna_persona_form" action='#' method='post' border='0'>
<table class='table table-hover table-responsive table-bordered'>


<tr>
<td>Altezza</td>
<td><input value="` + data.height_utente + `" type='number' name='height_utente' step="0.1" min="0.5" max="2.2" lang="en" id="altezza" class='form-control' required /></td>
</tr>
<tr>
<td>Peso utente</td>
<td><input value="` + data.weight_utente + `" type='number' name='weight_utente' step="0.1" min="0" max="200.0" lang="en" id="peso" class='form-control' required /></td></td>
</tr>

<tr>
<!-- hidden 'product id' to identify which record to update -->
<td><input value="` + data.giorno + `" name='giorno' id="giornata" type='hidden' /></td>
<!-- button to submit form -->
<td>
<button type='submit'  class='btn btn-info'>
<span class='fa fa-edit'></span> Aggiorna fumetto
</button>
</td>
</tr>
</table>
</form>`;
// inject to 'page-content' of our app
$("#contenuti_pagina").html(aggiorna_persona_html);
// chage page title
cambiaTitolo("Aggiorna persona");
});
});
// (*2*) send updated product data to the update service when the user submit the form
$(document).on('submit', '#aggiorna_persona_form', function(e) {
e.preventDefault();
// get form data
const form_data = JSON.stringify($(this).serializeObject());
console.log(form_data);
sendRequest("aggiorna.php", mostraPersone, "PUT", form_data);
});
});

下面是用于将DOM对象形式转换为javascript对象然后再转换为JSON的函数:*

$.fn.serializeObject = function() {
let o = {};
let a = this.serializeArray();
$.each(a, function() {
if (o[this.age_utente] !== undefined) {
if (!o[this.age_utente].push) {
o[this.age_utente] = [o[this.age_utente]];
}
o[this.age_utente].push(this.value || '');
} else {
o[this.age_utente] = this.value || '';
}
});
return o;
};

边缘控制台显示一个未定义的数组:

。{"undefined"("25","12"]}

我做错了什么?

serializeArray()返回的数组包含形式为{name: "field_name", value: field_value}的对象。所以没有this.age_utente,只有this.namethis.value

$.fn.serializeObject = function() {
let o = {};
let a = this.serializeArray();
$.each(a, function() {
if (!o[this.name]) {
o[this.name] = [];
}
o[this.name].push(this.value)
});
return o;
}

最新更新