javascript html 表单数组转 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11419298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:08:38  来源:igfitidea点击:

html form array to JSON

javascriptarraysjson

提问by Osvalda Kazlau?iūnait?

I'm having a dynamic html form containing several values, what I need is to add form data to JSON and post it to php page for insertion to mysql.

我有一个包含多个值的动态 html 表单,我需要的是将表单数据添加到 JSON 并将其发布到 php 页面以插入到 mysql。

Form:

形式:

<input type="text" name="name[]" id="p" />
<input type="text" name="manuf[]" id="k" size="3" />
<input type="text" name="item_pr[]" id="ka" size="10" />
<input type="text" name="price" id="su" size="10" disabled="disabled"/><br />

First tried to create JS array but cant figure out how get all values in one code row and how to convert to json and post to php:

首先尝试创建 JS 数组,但无法弄清楚如何在一个代码行中获取所有值以及如何转换为 json 并发布到 php:

var elementai = document.getElementsByName('name[]');
          for (var i = 0, j = elementai.length; i < j; i++) {
          var elementas = elementai[i];
          alert(elementas.value);
          }

回答by Nishu Tayal

Well, you can use jQuery for it as it is easy to use and less code to write. Though i am giving both solutions here.

好吧,您可以使用 jQuery,因为它易于使用且编写的代码更少。虽然我在这里给出了两种解决方案。

In JavaScript :

在 JavaScript 中:

$.fn.extractObject = function() {
  var accum = {};
  function add(accum, namev, value) {
    if (namev.length == 1)
      accum[namev[0]] = value;
    else {
      if (accum[namev[0]] == null)
        accum[namev[0]] = {};
      add(accum[namev[0]], namev.slice(1), value);
    }
  }; 
  this.find('input, textarea, select').each(function() {
    add(accum, $(this).attr('name').split('.'), $(this).val());
  });
  return accum;
}
// ...

var object = $('#testformId').extractObject();
console.log(object);

?Here is the demo: http://jsfiddle.net/G2XVq/

?这是演示http: //jsfiddle.net/G2XVq/

In jQuery :

在 jQuery 中:

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

$(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});?

(jQuery portion taken from here)

(jQuery 部分取自此处

Here is the demo: http://jsfiddle.net/sxGtM/3/

这是演示http: //jsfiddle.net/sxGtM/3/

for posting the data to php through javascript:

用于通过 javascript 将数据发布到 php:

 var str_json = JSON.stringify(myObject) //gives me the JSON string.

// AJAX XMLHttpRequest object in Javascript to send data to the server:
request= new XMLHttpRequestObject()
request.open("POST", "Phppage.php")
request.setRequestHeader("Content-type", "application/json", true)
request.send(str_json)

回答by RobB

The solution below utilizes the .map()function from jQuery to minimize the amount of code required to accurately reach your desired result.

下面的解决方案利用jQuery的.map()函数来最大限度地减少准确达到所需结果所需的代码量。

HTML:

HTML:

<input type="text" name="name" id="p" /> 
<input type="text" name="manuf" id="k" size="3" /> <input type="text" name="item_pr" id="ka" size="10" /> 
<input type="text" name="price" id="su" size="10" disabled="disabled"/>
<br /> 
<input type="button" id="go" value="Go >>" onclick="createJSONObject()" />

jQuery:

jQuery:

function createJSONObject(){
    var formValues = $('input[type=text]');
    var obj = {};
    $.map(formValues, function(n, i) {
        obj[n.name] = $(n).val();
    });

    console.log(JSON.stringify(obj));
}

Demo: http://jsfiddle.net/mBLkH/

演示:http: //jsfiddle.net/mBLkH/

The above code creates a jQuery object of your inputelements and then maps the nameattribute and valueof each element to the objobject variable. It then utilizes JSON.stringify(obj)to format the object into a viewable context.

上面的代码创建了一个input元素的 jQuery 对象,然后将每个元素的name属性 和映射valueobj对象变量。然后它利用JSON.stringify(obj)将对象格式化为可查看的上下文。

回答by iambriansreed

jQuery is over kill on this one.

jQuery 在这一点上已经完蛋了。

Proof: http://jsfiddle.net/iambriansreed/nTnhW/

证明:http: //jsfiddle.net/iambriansreed/nTnhW/

Pure JavaScript:

纯 JavaScript:

var input_ids = ['p','k','ka','su'];

for (var i = 0, j = input_ids.length; i < j; i++) {
    var element = document.getElementById(input_ids[i]);
    alert(element.value);
}?

回答by bokonic

If you want to just get your text inputs and you know the form's id:

如果您只想获取文本输入并且知道表单的 id:

var inputs = document.getElementById('myForm').getElementsByTagName('input');
var params = {};
for(var i=0; i < inputs.length; i++){
    var curr = inputs[i];
    if(curr.getAttribute('type')==='text')){
        params[curr.getAttribute('name')] = curr.value;
    }
}

Using jQuery to post:

使用 jQuery 发布:

$.post('myUrl',params,function(data){ console.log(data); });

Or with straight javascript: https://stackoverflow.com/a/8567146/1081941

或者直接使用 javascript:https: //stackoverflow.com/a/8567146/1081941