данные формы в json jquery

Convert form data to JavaScript object with jQuery

How do I convert all elements of my form to a JavaScript object?

59 Answers 59

serializeArray already does exactly that. You just need to massage the data into your required format:

Watch out for hidden fields which have the same name as real inputs as they will get overwritten.

Convert forms to JSON like a boss

The current source is on GitHub and Bower.

$ bower install jquery-serialize-object

The following code is now deprecated.

The following code can take work with all sorts of input names; and handle them just as you’d expect.

Usage

The Sorcery (JavaScript)

And a CoffeeScript version for your coding convenience:

I like using Array.prototype.reduce because it’s a one-liner, and it doesn’t rely on Underscore.js or the like:

IMPORTANT NOTE: Forms with inputs that have duplicate name attributes are valid HTML, and is actually a common approach. Using any of the answers in this thread will be inappropriate in that case (since object keys must be unique).

All of these answers seemed so over the top to me. There’s something to be said for simplicity. As long as all your form inputs have the name attribute set this should work just jim dandy.

[UPDATE 2020]

With a simple oneliner in vanilla js that leverages fromEntries (as always, check browser support):

For example: If you have an HTML form similar to the one below:

But it should be generated just like the JSON below, and does not become an object like the following with all the other answers. So if anyone wants to bring something like the following JSON, try the JS code below.

If you are using Underscore.js you can use the relatively concise:

Ok, I know this already has a highly upvoted answer, but another similar question was asked recently, and I was directed to this question as well. I’d like to offer my solution as well, because it offers an advantage over the accepted solution: You can include disabled form elements (which is sometimes important, depending on how your UI functions)

Here is my answer from the other SO question:

Note that for this to work, each of your inputs will need a name attribute, which will be the name of the property of the resulting object.

This function should handle multidimensional arrays along with multiple elements with the same name.

I’ve been using it for a couple years so far:

One-liner (no dependencies other than jQuery), uses fixed object binding for function passsed to map method.

suitable for progressive web apps (one can easily support both regular form submit action as well as ajax requests)

I found a problem with Tobias Cohen’s code (I don’t have enough points to comment on it directly), which otherwise works for me. If you have two select options with the same name, both with value=»», the original code will produce «name»:»» instead of «name»:[«»,»»]

I think this can fixed by adding » || o[this.name] == »» to the first if condition:

Simplicity is best here. I’ve used a simple string replace with a regular expression, and they worked like a charm thus far. I am not a regular expression expert, but I bet you can even populate very complex objects.

Using maček’s solution, I modified it to work with the way ASP.NET MVC handles their nested/complex objects on the same form. All you have to do is modify the validate piece to this:

This will match and then correctly map elements with names like:

There is a plugin to do just that for jQuery, jquery.serializeJSON. I have used it successfully on a few projects now. It works like a charm.

the simplest and most accurate way i found for this problem was to use bbq plugin or this one (which is about 0.5K bytes size).

it also works with multi dimensional arrays.

I prefer this approach because: you don’t have to iterate over 2 collections, you can get at things other than «name» and «value» if you need to, and you can sanitize your values before you store them in the object (if you have default values that you don’t wish to store, for example).

Only tested in Firefox.

Taking advantage of ES6 goodness in a one liner:

I like samuels version, but I believe it has a small error. Normally JSON is sent as

so the function IMO should read:

and to wrap it in data array (as commonly expected, too), and finally send it as astring App.stringify( )

For the stringify look at Question 3593046 for the lean version, at json2.js for the every-eventuality-covered version. That should cover it all 🙂

Turn anything into an object (not unit tested)

The output of test:

For a quick, modern solution, use the JSONify jQuery plugin. The example below is taken verbatim from the GitHub README. All credit to Kushal Pandya, author of the plugin.

If you want to do a jQuery POST with this JSON object:

I found a problem with the selected solution.

When using forms that have array based names the jQuery serializeArray() function actually dies.

I have a PHP framework that uses array-based field names to allow for the same form to be put onto the same page multiple times in multiple views. This can be handy to put both add, edit and delete on the same page without conflicting form models.

Since I wanted to seralize the forms without having to take this absolute base functionality out I decided to write my own seralizeArray():

Please note: This also works outside of form submit() so if an error occurs in the rest of your code the form won’t submit if you place on a link button saying «save changes».

Also note that this function should never be used to validate the form only to gather the data to send to the server-side for validation. Using such weak and mass-assigned code WILL cause XSS, etc.

The point is you may actually want to build a form so that it has a structure itself, so let’s say you want to make a form where the user inserts his favourite places in town: you can imagine this form to represent a

XML element containing a list of places the user likes thus a list of

How cool would it be to have a JSON object out of this which would represent this exact structure so you’ll be able to either:

OK, so now we need to think how a form can represent an XML file.

As you can see in this form, we’re breaking the rule of unique names, but this is OK because they’ll be converted into an array of element thus they’ll be referenced only by their index inside the array.

At this point you can see how there’s no name=»array[]» like name inside the form and everything is pretty, simple and semantic.

Now we want this form to be converted into a JSON object which will look like this:

To do this I have developed this jQuery plugin here which someone helped optimizing in this Code Review thread and looks like this:

I also made this one blog post to explain this more.

This converts everything in a form to JSON (even radio and check boxes) and all you’ll have left to do is call

Источник

Сериализация сложной формы в объект JSON с помощью jQuery

Я искал несколько часов и не нашел ответа. Пожалуйста, прочитайте весь вопрос, прежде чем флеймить! 🙂

у меня есть форма следующего вида:

и нужно иметь возможность сериализовать его до этого:

Я пробовал большинство ответов на SO, включая библиотеки jquery-json, и большинство из них возвращают что-то вроде этого:

Это нечто я не могу использовать! : P

спасибо все вперед.

6 ответов

попробуйте этот код, который я написал для вас. Отлично работает для меня, просто используя ваш результат данных. Вы можете работать над этим и сделать простой плагин jQuery.

образец нужен JSON.stringify для полной работы.

существует также следующая библиотека

Это очень хорошо для меня. Это не должно иметь библиотеку form2js.

для сериализации данных формы я использовал этот код.

Если у вас есть какие-либо сомнения, пожалуйста, не стесняйтесь добавлять комментарий.

С этой структурой я не думаю, что любая библиотека JSON может выполнять всю работу. Итак, я думаю, что проще написать наш собственный цикл преобразования.

вот код для вашей сериализации:http://jsfiddle.net/7MAUv/1/

логика довольно проста, секрет в eval для запуска строк, таких как динамические команды. Я старался сделать это как можно проще, почти все строки комментируются.

BTW, чувствует свободным сделать вопросы.

Это не совсем то, что вы просили, но если вы используете библиотеку jQuery и вам нужна сложная форма, сериализованная с целью отправки ее в ajax, вы можете использовать sth как это

Источник

Получение данных формы на jQuery

данные формы в json jquery. данные формы в json jquery фото. картинка данные формы в json jquery. смотреть фото данные формы в json jquery. смотреть картинку данные формы в json jquery.

Статья, в которой рассмотрим различные способы простого извлечения данных из HTML формы. А именно познакомимся с тем, как это сделать с помощью метода each, а также методов jQuery специально предназначенных для этого. Объект FormData в данной статье рассматривать не будем.

jQuery – Получения данных формы с помощью метода each

Работу по извлечению данных c элементов формы посредством метода each рассмотрим на примере.

В минимальном варианте данная последовательность действий состоит из создания пустого объекта JavaScript, перебора элементов формы с помощью метода each и добавления в созданный объект данных соответствующих значениям определённых атрибутов ( name и value ) элементов.

При необходимости, после получения данных формы можно добавить различные проверки. Это предотвратит отправку не валидных данных на сервер.

Методы jQuery serialize и serializeArray оличаются друг от друга только форматом вывода данных. Метод serialize обычно применяется в том случае, когда результат (данные формы) необходимо положить в строку HTTP запроса. Метод serializeArray наоборот, используется тогда, когда результат, который он предоставил, как правило, ещё необходимо обработать.

Внимание: Методы serialize и serializeArray не сериализуют данные из элементов, которые используются для выбора файлов.

PHP код, обрабатывающий ajax запрос на сервере:

Вышеприведёный код просто формирует строку из данных формы на сервере, которая затем будет отправлена клиенту (браузеру).

Сериализация формы с помощью методов jQuery serialize и serializeArray данные формы в json jquery. данные формы в json jquery фото. картинка данные формы в json jquery. смотреть фото данные формы в json jquery. смотреть картинку данные формы в json jquery.

Источник

Converting serialized form’s data to json object

I have a cshtml like the following

In my javascript(in a separate javascript file), I’m trying to serialize this form and convert it into a JSON object.

данные формы в json jquery. данные формы в json jquery фото. картинка данные формы в json jquery. смотреть фото данные формы в json jquery. смотреть картинку данные формы в json jquery.

I have tried doing this

But I get this error:

7 Answers 7

Change your statement

Use the code below.

Use this function. This will work only with jquery.

You can use this for make a json with all fields of form.

Jquery example:

Pure JavaScript with FormData:

данные формы в json jquery. данные формы в json jquery фото. картинка данные формы в json jquery. смотреть фото данные формы в json jquery. смотреть картинку данные формы в json jquery.

данные формы в json jquery. данные формы в json jquery фото. картинка данные формы в json jquery. смотреть фото данные формы в json jquery. смотреть картинку данные формы в json jquery.

A modern interpretation. babel stage-2 preset is required to compile the object spread operator

You could do the following to convert a serialize data to json object, this would take the array of fields in form and iterate over it asigning the keys and values to a new object.

Not the answer you’re looking for? Browse other questions tagged jquery asp.net-mvc json serialization or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.11.5.40661

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Использование jQuery и JSON для заполнения форм?

мне было интересно, как popssible заполнять формы с помощью JSON?

у меня есть строка JSON, которую я получаю с помощью php json_encode() И я хочу использовать строку JSON для заполнения элементов управления формой (например, textarea или text input).

Как я могу достичь этого без использования внешних плагинов (например, jQuery populate plugin, который я видел).

это то, что я получаю от json_encode()

10 ответов

здесь есть проблема с textarea, затем я изменяю его на значение переключателя по умолчанию

используйте это, чтобы присвоить значения многим элементам управления:

для текстовых элементов управления (т. е. без радио или флажков) вы можете сделать простую версию функции заполнения:

Спасибо Nowshath. У меня получилось. Я добавил дополнительную проверку в вашей версии, чтобы иметь возможность заполнять параметры выбора.

С небольшими улучшениями (кроме переключателей):

пример Usecase с функциями выше:

со всеми примерами выше, хотя:

необходимо изменить на

для предотвращения синтаксической ошибки с помощью в jQuery

обратите внимание, что массивы списков должны быть записаны с числами (например, fruit[0], а не fruit []), чтобы работать с этой функцией.

Это апендикс к ответу @Nowshath

это работает и для многоуровневых объектов

Это может стать довольно сложным. Лучше всего использовать инструмент для анализа вашего JSON. Вы можете создавать простые формы довольно легко, но вам все равно нужно разобрать его.

или вы можете использовать ext4.

для странного, но допустимого синтаксиса JSON, такого как

У нас был этот странный синтаксис, используемый в нашем приложении, и мы обошли, написав логику, как указано выше.

Я обнаружил, что исходный скрипт не играл хорошо с именами array[] из-за отсутствующих кавычек в селекторе имен:

У меня была та же проблема, и я разработал версию, показанную выше немного дальше. Теперь можно установить отдельные флажки, возвращающие значение, а также группы, возвращающие массив имен. Кодирование тестируется, используется и работает правильно.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *