html/php表单到JSON的问题


Problems with html/php Form to JSON

我意识到我可能应该为此使用angular,但我不能为这个项目做到这一点。

我想做的是,很容易地将一个表单转换为javascript对象,该对象将通过AJAX传递。

php脚本应该简单地处理对象,并对它执行我需要的操作

问题是,我的对象格式不正确。

因此,一个包含如下字段的表单:

<input type="text" name="chart_data[1][value]" />

但不管出于什么原因,我的物体看起来是这样的!

chart_data[1: Object
color: "#726d86"
highlight: "#4f4868"
label: "Transportation"
value: "10"

闭合支架不见了!chart_data[1

我尝试了两种不同的函数来尝试将数据转换为对象。两者似乎都造成了同样的问题。

Javascript仍然是我最薄弱的语言,所以任何帮助都将不胜感激!

(function( $ ) {
    $.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;
    };
})(jQuery);
/*!
 * jQuery serializeObject - v0.2 - 1/20/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($,undefined){
    '$:nomunge'; // Used by YUI compressor.
    $.fn.serializeObject = function(){
        var obj = {};
        $.each( this.serializeArray(), function(i,o){
            var n = o.name,
                v = o.value;
            obj[n] = obj[n] === undefined ? v
                : $.isArray( obj[n] ) ? obj[n].concat( v )
                : [ obj[n], v ];
        });
        return obj;
    };
})(jQuery);

您不需要执行任何操作。jQuery内置的serialize()将为您处理

$('#formID').on('submit',function(e){
   e.preventDefault();
   $.post(url, $(this).serialize(), function(resp){
      // do something with response
   }[,dataType])
});

然后在php中,由所讨论的input表示的数组将使用可用

$chartDataArray = $_POST['chart_data'];