Как сохранить эту форму на потом, сохраняя сериализованные данные в JSON?

[Решено] У меня есть большая HTML-форма с двумя таблицами, одна маленькая со статическими полями и именами. Вторая большая таблица имеет динамически добавленные строки с помощью кнопки, все поля в этой большой таблице имеют в строке уникальное имя + номер, например: sku_code_input_1, что представляет собой идентификатор строки, который также отображается в первом столбце. Поскольку идентификатор строки не представляет реальный идентификатор строки, потому что мне пришлось добавить несколько «пустых строк», где разрывы страниц для печати. Этот код возьмет все значения из этих полей ввода и вернет мне строку, что, как я полагаю, предназначено для POST-цели в URL-адресе.


     function returnArrayValues() {
        var countRow = $('#sku_details_list tr').length -3;
        var str = $( "#inboundList" ).serialize();
        
        $( "#results" ).text( countRow + " " + str); //just to show it on display
        }
      /* Results showed on screen:
      0 create_time=2020-12- 
    12T09%3A04&container_noS=MXASDOFSA&ic_numbS=IC06956251&customer_code=985652&
    unload_date=2020-12-02&
    unload_name=cxzczx&date_and_time=2020-12-10T09%3A24&
    sorting_date=2020-12-11&sorting_name=czxc&gate_numbe=95&
    putaway_date=2020-12-11&putaway_name=zxcasdas&old_ro_numb=&
    confirm_date=&confirm_name=&in_box_date=&in_box_name=&pallets_qtty_1=12&
    boxes_on_pallet_1=1&sku_code_input_1=1516566&expected_qtty_box_1=12&
    received_box_qtty_1=12&putaway_area_1=122.2.2.2&pallets_qtty_2=20&
    boxes_on_pallet_2=5&sku_code_input_2=KASDJ-XZC-56
    &expected_qtty_box_2=100&received_box_qtty_2=100&putaway_area_2=333.6.6.4
    ...... */

Я не знаю, как я могу преобразовать, сохранить этот тип вывода, возможно, в файле JSON, так как хранение этого в базе данных MySQL может быть слишком большим, учитывая, что может быть 174 строки. container_noS, ic_numbS и date_and_time поля, которые требуется, и я хотел бы использовать их в качестве ключа для возврата остальной части формы.

Я думаю, что массив должен выглядеть примерно так? Где Array[1] будут данные из другой формы, и я мог бы использовать первые 3 значения, чтобы найти, какую форму я ищу для вызова значений.

Массив[0]{{'container_noS':'MXASDOFSA', 'ic_numbS': 'IC06956251', 'date_and_time': '2020-12-10T09%3A24'} SubArray[]{'customer_code': '985652', 'дата_выгрузки': '2020-12-02', ...}}

Массив1{{'container_noS':'XASDAS', 'ic_numbS': 'IC77777', 'date_and_time': '2020-10-11T09%3A24'} SubArray[]{'customer_code': '123452', 'дата_выгрузки': '2020-10-02', ...}}

Полный код здесь или макет HTML-таблицы ниже:

<body class = "print">
<form class = "container-fluid" method = "post" id = "inboundList" enctype = "application/x-www-form-urlencoded">
    <div id = "no-print" style = "margin-left:10%;">
        <button type = "button" id = "save_button" style = "margin: 0 20px 20px 0;" onclick = "returnArrayValues()">Save</button>
        <button type = "button" id = "print_button" style = "margin: 0 20px 20px 0;" onclick = "window.print()">Print</button>
        <button type = "reset" id = "reset_button" style = "margin: 0 20px 20px 0;">Reset Form</button>
        <button type = "close" id = "cancel_button" style = "margin: 0 20px 20px 0;">Discard</button>
    
    </div>
    <div style = "width:20.7cm;  background-color: yellow; page-break-inside:auto;  ;" id = "printPageDiv"> <!-- Start of DIV what will be printed -->
    <div style = "position:relative;"> <!-- Header of Page with logo and Container No. -->
    <img src='../../images/id_print_logo.png' height = "72px" width = "182px">
    <label>Created:<input type = "datetime-local" step = "60" pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" 
    id = "create_time" name = "create_time" readonly style = "width:180px; text-align:center;" value = "<?php echo date('Y-m-d\TH:i')?>"></input></label>
    
    <label style = "font-size:15px;font_weight:bold;  margin-left: 20px">Container Number: 
        <input type = "text" name = "container_noS" id = "container_noS" style = "font-size:15px; font_weight:bold; text-align:center; width: 180px;" maxlength = "16" required></input></label>
    </div>  
    <!-- IC Number with its Barcode  -->
    <div style = "position:relative; margin-top:5px; height:2cm">
    <label style = "float:right; font_weight:bold;width:250px; ">IC Number: <input required type = "text" name = "ic_numbS" id = "ic_numbS" onchange = "changeTest(this.form)" 
    maxlength = "16" style = "font-size:20px; font_weight:bold; text-align:center;"></input></label>
    <div id = "insertBarcodeHere"></div>
    </div>  
<div class = "row"></div> 
<table id = "rcv_head_tmpl"> <!-- Start of header table -->
    <tr><th></th><th></th><th></th><th>Date: </th><th>Name: </th></tr>
    <tr><th>Client: </th><td><input type = "text" name = "customer_code"></input></td>
    <th>Unloading: </th><td><input type = "date" name = "unload_date"></td>
    <td><input type = "text" name = "unload_name"></td></tr>
    
    <tr><th>Date and Time: </th><td><input type = "datetime-local" step = "60" pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}"  
    name = "date_and_time" required></input></td>
    
    <th>Sorting: </th><td><input type = "date" name = "sorting_date"></td>
    <td><input type = "text" name = "sorting_name"></td></tr>
    
    <tr><th>Gate: </th><td><input type = "text" name = "gate_numbe"></input></td>
    <th>Put away: </th><td><input type = "date" name = "putaway_date"></td>
    <td><input type = "text" name = "putaway_name"></td></tr>
    
    <tr><th>OLD RO: </th><td><input type = "text" name = "old_ro_numb"></input></td>
    <th>Confirmation: </th><td><input type = "date" name = "confirm_date"></td>
    <td><input type = "text" name = "confirm_name"></td></tr>
    
    <tr><th></th><td></td>
    <th>Counting pcs in box: </th><td><input type = "date" name = "in_box_date"></td>
    <td><input type = "text" name = "in_box_name"></td></tr>    

</table  > <!--end of header table -->
<table id = "sku_details_list"  class = "tablesorter" style = " border-spacing: 1px;"> <!-- Start of SKU list table -->

    <tr><th style = "width: 3%;">ID: </th><th style = "width: 8%;">Total Pallets: </th><th style = "width: 8%;">Boxes on Pallet: </th><th style = "width: 12%;">Old Location: </th>
    <th style = "width: 20%;">SKU Code: </th><th style = "width: 8%;">Expected Qtty: </th><th style = "width: 8%;">Received Boxes: </th><th style = "width: 12%;">Putaway Location: </th></tr>
    
    <tr><td>1</td><td><input type = "text" name = "pallets_qtty_1"></input></td>
                        <td><input type = "text" name = "boxes_on_pallet_1"></input></td>
                        <td id = "return_oldLocation1"></td>
                        <td><input type = "text" name = "sku_code_input_1" onchange = "showOldLocations(this.value,this)"></input></td>
                        <td><input type = "text" name = "expected_qtty_box_1"></input></td>
                        <td><input type = "text" name = "received_box_qtty_1"></input></td>
                        <td><input type = "text" name = "putaway_area_1"></input></td></tr>
        
    <tr><td>2</td><td><input type = "text" name = "pallets_qtty_2"></input></td>
                        <td><input type = "text" name = "boxes_on_pallet_2"></input></td>
                        <td id = "return_oldLocation2"></td>
                        <td><input type = "text" name = "sku_code_input_2" onchange = "showOldLocations(this.value,this)"></input></td>
                        <td><input type = "text" name = "expected_qtty_box_2"></input></td>
                        <td><input type = "text" name = "received_box_qtty_2"></input></td>
                        <td><input type = "text" name = "putaway_area_2"></input></td></tr>

</table> <!-- End of SKU list table -->
</div> <!-- div for page to be printed -->  
<button type = "button" id = "row_button">Add New Row</button>

</div>
  </form>

Когда я пробую другую функцию для хранения данных, мне возвращается [object Object]. Когда я конвертирую это с помощью serialize(), что я считаю неправильным, я получаю тот же результат, что и с моей первой функцией. Итак, вопрос все еще здесь, как я могу прочитать эти значения [object Object], что, как я должен полагать, должно быть правильным выводом, который я ищу.

 $('#inboundList').submit(function(e) {
e.preventDefault(); 
var form = $(this); 
form.children('input').each(function() {
    form.data($(this).attr('name'), $(this).attr('value'));
}); 
var xxx = stringify([form]);
$( "#results" ).text( xxx );
});

ОБНОВЛЕНИЕ: я пытаюсь использовать замену символов = и &, чтобы сделать его синтаксисом JSON.

 function returnArrayValues() {
var countRow = $('#sku_details_list tr').length -3;
var str = $( "#inboundList" ).serialize();
var resUlt = str.replace(/=&/g,'": "", "').replace(/=/g,'": "').replace(/&/g,'", "');

$( "#results" ).text( '"table_rows": "'+countRow + '", "' + resUlt + '"'); //just to show it on display

  } 
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
191
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Вы можете использовать serializeArray и reduce для преобразования данных формы в объект:

// ES5 version

var data = $('#inboundList').serializeArray()
  .reduce(function(accu, field) {
    accu[field.name] = field.value;
    return accu;
  }, {});

console.info(data);

// ES6 version

var data = $('#inboundList').serializeArray()
  .reduce((accu, {name, value}) => ({ ...accu, [name]: value }), {});

console.info(data);
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class = "container-fluid" method = "post" id = "inboundList" enctype = "application/x-www-form-urlencoded">
    <div id = "no-print" style = "margin-left:10%;">
        <button type = "button" id = "save_button" style = "margin: 0 20px 20px 0;" onclick = "returnArrayValues()">Save</button>
        <button type = "button" id = "print_button" style = "margin: 0 20px 20px 0;" onclick = "window.print()">Print</button>
        <button type = "reset" id = "reset_button" style = "margin: 0 20px 20px 0;">Reset Form</button>
        <button type = "close" id = "cancel_button" style = "margin: 0 20px 20px 0;">Discard</button>
    
    </div>
    <div style = "width:20.7cm;  background-color: yellow; page-break-inside:auto;  ;" id = "printPageDiv"> <!-- Start of DIV what will be printed -->
    <div style = "position:relative;"> <!-- Header of Page with logo and Container No. -->
    <img src='../../images/id_print_logo.png' height = "72px" width = "182px">
    <label>Created:<input type = "datetime-local" step = "60" pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" 
    id = "create_time" name = "create_time" readonly style = "width:180px; text-align:center;" value = "<?php echo date('Y-m-d\TH:i')?>"></input></label>
    
    <label style = "font-size:15px;font_weight:bold;  margin-left: 20px">Container Number: 
        <input type = "text" name = "container_noS" id = "container_noS" style = "font-size:15px; font_weight:bold; text-align:center; width: 180px;" maxlength = "16" required></input></label>
    </div>  
    <!-- IC Number with its Barcode  -->
    <div style = "position:relative; margin-top:5px; height:2cm">
    <label style = "float:right; font_weight:bold;width:250px; ">IC Number: <input required type = "text" name = "ic_numbS" id = "ic_numbS" onchange = "changeTest(this.form)" 
    maxlength = "16" style = "font-size:20px; font_weight:bold; text-align:center;"></input></label>
    <div id = "insertBarcodeHere"></div>
    </div>  
<div class = "row"></div> 
<table id = "rcv_head_tmpl"> <!-- Start of header table -->
    <tr><th></th><th></th><th></th><th>Date: </th><th>Name: </th></tr>
    <tr><th>Client: </th><td><input type = "text" name = "customer_code"></input></td>
    <th>Unloading: </th><td><input type = "date" name = "unload_date"></td>
    <td><input type = "text" name = "unload_name"></td></tr>
    
    <tr><th>Date and Time: </th><td><input type = "datetime-local" step = "60" pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}"  
    name = "date_and_time" required></input></td>
    
    <th>Sorting: </th><td><input type = "date" name = "sorting_date"></td>
    <td><input type = "text" name = "sorting_name"></td></tr>
    
    <tr><th>Gate: </th><td><input type = "text" name = "gate_numbe"></input></td>
    <th>Put away: </th><td><input type = "date" name = "putaway_date"></td>
    <td><input type = "text" name = "putaway_name"></td></tr>
    
    <tr><th>OLD RO: </th><td><input type = "text" name = "old_ro_numb"></input></td>
    <th>Confirmation: </th><td><input type = "date" name = "confirm_date"></td>
    <td><input type = "text" name = "confirm_name"></td></tr>
    
    <tr><th></th><td></td>
    <th>Counting pcs in box: </th><td><input type = "date" name = "in_box_date"></td>
    <td><input type = "text" name = "in_box_name"></td></tr>    

</table  > <!--end of header table -->
<table id = "sku_details_list"  class = "tablesorter" style = " border-spacing: 1px;"> <!-- Start of SKU list table -->

    <tr><th style = "width: 3%;">ID: </th><th style = "width: 8%;">Total Pallets: </th><th style = "width: 8%;">Boxes on Pallet: </th><th style = "width: 12%;">Old Location: </th>
    <th style = "width: 20%;">SKU Code: </th><th style = "width: 8%;">Expected Qtty: </th><th style = "width: 8%;">Received Boxes: </th><th style = "width: 12%;">Putaway Location: </th></tr>
    
    <tr><td>1</td><td><input type = "text" name = "pallets_qtty_1"></input></td>
                        <td><input type = "text" name = "boxes_on_pallet_1"></input></td>
                        <td id = "return_oldLocation1"></td>
                        <td><input type = "text" name = "sku_code_input_1" onchange = "showOldLocations(this.value,this)"></input></td>
                        <td><input type = "text" name = "expected_qtty_box_1"></input></td>
                        <td><input type = "text" name = "received_box_qtty_1"></input></td>
                        <td><input type = "text" name = "putaway_area_1"></input></td></tr>
        
    <tr><td>2</td><td><input type = "text" name = "pallets_qtty_2"></input></td>
                        <td><input type = "text" name = "boxes_on_pallet_2"></input></td>
                        <td id = "return_oldLocation2"></td>
                        <td><input type = "text" name = "sku_code_input_2" onchange = "showOldLocations(this.value,this)"></input></td>
                        <td><input type = "text" name = "expected_qtty_box_2"></input></td>
                        <td><input type = "text" name = "received_box_qtty_2"></input></td>
                        <td><input type = "text" name = "putaway_area_2"></input></td></tr>

</table> <!-- End of SKU list table -->
</div> <!-- div for page to be printed -->  
<button type = "button" id = "row_button">Add New Row</button>

</div>
  </form>

Спасибо, наконец-то это похоже на результат, который я искал. Раньше, когда я использовал этот serializeArray(), я получал [object Object] вместо значений. И в консоли я не мог видеть никаких значений, только разные параметры.

michal 12.12.2020 12:35
[object Object] — это результат вызова .toString() по умолчанию для объекта. Это также происходит автоматически, когда вы пытаетесь объединить объект со строкой вроде этой console.info("output: " + someObject) или вот такой $('something').text(someObject). Чтобы осмотреть объект, вы всегда должны использовать console.info(someObject) или console.info("info", someObject).
Đinh Carabus 12.12.2020 13:47

Могу я попросить вас еще об одном? Можно ли сделать это многомерным массивом перед отправкой на PHP? Я хотел бы указать начальные значения container_noS, ic_numbS and date_and_time + количество строк, что было сделано в начале функции, что отправляет все эти данные в PHP с помощью var countRow = $('#sku_details_list tr').length -3;

michal 14.12.2020 11:02

@michal Я не совсем уверен, что вы подразумеваете под «многомерным массивом» в данном случае. Можете ли вы предоставить полный результат, чтобы я мог попытаться выяснить, чего именно вы хотите достичь? Вы можете добавить желаемый результат в качестве редактирования исходного вопроса.

Đinh Carabus 14.12.2020 18:54

Если вы хотите сериализовать некоторые строки таблицы отдельно, вы можете сделать что-то вроде этого:

// Helper function that serializes each input element 
// of a specified parent element.
var serialize = function(element) {
  return $(element).find(':input').get()
    .reduce(function(accu, field) {
      accu[field.name] = field.value;
      return accu;
    }, {});
};

var data = serialize('#rcv_head_tmpl'); // add base-table data
 
// add sub-table data as "rows"
data.rows = $("#sku_details_list") // find sub-table
  .find('tr:not(:first)') // get each row except the first (header)
  .get().map(serialize); // serialize each row

console.info(data);
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class = "container-fluid" method = "post" id = "inboundList" enctype = "application/x-www-form-urlencoded">
    <div id = "no-print" style = "margin-left:10%;">
        <button type = "button" id = "save_button" style = "margin: 0 20px 20px 0;" onclick = "returnArrayValues()">Save</button>
        <button type = "button" id = "print_button" style = "margin: 0 20px 20px 0;" onclick = "window.print()">Print</button>
        <button type = "reset" id = "reset_button" style = "margin: 0 20px 20px 0;">Reset Form</button>
        <button type = "close" id = "cancel_button" style = "margin: 0 20px 20px 0;">Discard</button>
    
    </div>
    <div style = "width:20.7cm;  background-color: yellow; page-break-inside:auto;  ;" id = "printPageDiv"> <!-- Start of DIV what will be printed -->
    <div style = "position:relative;"> <!-- Header of Page with logo and Container No. -->
    <img src='../../images/id_print_logo.png' height = "72px" width = "182px">
    <label>Created:<input type = "datetime-local" step = "60" pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" 
    id = "create_time" name = "create_time" readonly style = "width:180px; text-align:center;" value = "<?php echo date('Y-m-d\TH:i')?>"></input></label>
    
    <label style = "font-size:15px;font_weight:bold;  margin-left: 20px">Container Number: 
        <input type = "text" name = "container_noS" id = "container_noS" style = "font-size:15px; font_weight:bold; text-align:center; width: 180px;" maxlength = "16" required></input></label>
    </div>  
    <!-- IC Number with its Barcode  -->
    <div style = "position:relative; margin-top:5px; height:2cm">
    <label style = "float:right; font_weight:bold;width:250px; ">IC Number: <input required type = "text" name = "ic_numbS" id = "ic_numbS" onchange = "changeTest(this.form)" 
    maxlength = "16" style = "font-size:20px; font_weight:bold; text-align:center;"></input></label>
    <div id = "insertBarcodeHere"></div>
    </div>  
<div class = "row"></div> 
<table id = "rcv_head_tmpl"> <!-- Start of header table -->
    <tr><th></th><th></th><th></th><th>Date: </th><th>Name: </th></tr>
    <tr><th>Client: </th><td><input type = "text" name = "customer_code"></input></td>
    <th>Unloading: </th><td><input type = "date" name = "unload_date"></td>
    <td><input type = "text" name = "unload_name"></td></tr>
    
    <tr><th>Date and Time: </th><td><input type = "datetime-local" step = "60" pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}"  
    name = "date_and_time" required></input></td>
    
    <th>Sorting: </th><td><input type = "date" name = "sorting_date"></td>
    <td><input type = "text" name = "sorting_name"></td></tr>
    
    <tr><th>Gate: </th><td><input type = "text" name = "gate_numbe"></input></td>
    <th>Put away: </th><td><input type = "date" name = "putaway_date"></td>
    <td><input type = "text" name = "putaway_name"></td></tr>
    
    <tr><th>OLD RO: </th><td><input type = "text" name = "old_ro_numb"></input></td>
    <th>Confirmation: </th><td><input type = "date" name = "confirm_date"></td>
    <td><input type = "text" name = "confirm_name"></td></tr>
    
    <tr><th></th><td></td>
    <th>Counting pcs in box: </th><td><input type = "date" name = "in_box_date"></td>
    <td><input type = "text" name = "in_box_name"></td></tr>    

</table  > <!--end of header table -->
<table id = "sku_details_list"  class = "tablesorter" style = " border-spacing: 1px;"> <!-- Start of SKU list table -->

    <tr><th style = "width: 3%;">ID: </th><th style = "width: 8%;">Total Pallets: </th><th style = "width: 8%;">Boxes on Pallet: </th><th style = "width: 12%;">Old Location: </th>
    <th style = "width: 20%;">SKU Code: </th><th style = "width: 8%;">Expected Qtty: </th><th style = "width: 8%;">Received Boxes: </th><th style = "width: 12%;">Putaway Location: </th></tr>
    
    <tr><td>1</td><td><input type = "text" name = "pallets_qtty_1"></input></td>
                        <td><input type = "text" name = "boxes_on_pallet_1"></input></td>
                        <td id = "return_oldLocation1"></td>
                        <td><input type = "text" name = "sku_code_input_1" onchange = "showOldLocations(this.value,this)"></input></td>
                        <td><input type = "text" name = "expected_qtty_box_1"></input></td>
                        <td><input type = "text" name = "received_box_qtty_1"></input></td>
                        <td><input type = "text" name = "putaway_area_1"></input></td></tr>
        
    <tr><td>2</td><td><input type = "text" name = "pallets_qtty_2"></input></td>
                        <td><input type = "text" name = "boxes_on_pallet_2"></input></td>
                        <td id = "return_oldLocation2"></td>
                        <td><input type = "text" name = "sku_code_input_2" onchange = "showOldLocations(this.value,this)"></input></td>
                        <td><input type = "text" name = "expected_qtty_box_2"></input></td>
                        <td><input type = "text" name = "received_box_qtty_2"></input></td>
                        <td><input type = "text" name = "putaway_area_2"></input></td></tr>

</table> <!-- End of SKU list table -->
</div> <!-- div for page to be printed -->  
<button type = "button" id = "row_button">Add New Row</button>

</div>
  </form>

Я думаю, было бы еще проще, если бы вы поместили каждый раздел в отдельный элемент form. Затем вы можете просто использовать serializeArray для каждого элемента form и, наконец, объединить результаты.

Другие вопросы по теме