0

注意:我已经看到了很多关于此的问题,但每个问题的答案都略有不同,由于答案不同,我想知道什么是规范或最佳实践。他们都不清楚为什么会有差异,或者何时使用其中一个。有些只是过时了。

Jquery 1.8.0 版,示例使用coffeescript。

我有一个带有数据的表单,点击提交获取数据并发布它的方式是根据我所读到的三件事之一:(如果下面的示例中有未声明的变量,请假设他们已经分配到别处)

1:

data = $.param(form.serializeArray())
$.ajax( url, {
  headers: { 
    Accept : "application/json",
    "Content-Type": "application/json"
  },
  dataType: "json",
  type: "POST",
  data: data,

发布 jquery .serializeArray(); 通过ajax输出

2. 除此行外,同 (1):

data = JSON.stringify(form.serializeArray())

使用 JQuery 通过 ajax 动态发送 json 格式的表单数据

3. 除此行外,同 (1):

data = form.serialize()

http://api.jquery.com/jQuery.post/#example-3

这也许可以解释为什么最好使用$.param,但这是一篇关于 jQuery 1.4 的旧帖子。

4

1 回答 1

0

这是来自 (http://jquery.com/) 版本 1.8.2 的 jquery 源,用于在 ajax 调用之前构建参数


function buildParams( prefix, obj, traditional, add ) {
    var name;

    if ( jQuery.isArray( obj ) ) {
        // Serialize array item.
        jQuery.each( obj, function( i, v ) {
            if ( traditional || rbracket.test( prefix ) ) {
                // Treat each array item as a scalar.
                add( prefix, v );

            } else {
                // If array item is non-scalar (array or object), encode its
                // numeric index to resolve deserialization ambiguity issues.
                // Note that rack (as of 1.0.0) can't currently deserialize
                // nested arrays properly, and attempting to do so may cause
                // a server error. Possible fixes are to modify rack's
                // deserialization algorithm or to provide an option or flag
                // to force array serialization to be shallow.
                buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
            }
        });

    } else if ( !traditional && jQuery.type( obj ) === "object" ) {
        // Serialize object item.
        for ( name in obj ) {
            buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
        }

    } else {
        // Serialize scalar item.
        add( prefix, obj );
    }
}

从列出的代码中,您可以看到上面列出的所有“方式”都在上面列出的函数中的参数处理中进行处理,并最终以相同的字符串化版本结束

于 2012-09-27T19:56:15.840 回答