html / php Form到JSON的问题

时间:2015-10-28 22:00:55

标签: javascript php jquery arrays json

我意识到我应该使用角度来做这个,但是我不能为这个项目做那个。

我正在尝试做的,很容易将表单转换为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);

1 个答案:

答案 0 :(得分:3)

你不应该做任何这些。 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'];