【问题标题】:3 ways to POST form data via Jquery's ajax functions to route that accepts JSON通过 Jquery 的 ajax 函数 POST 表单数据以路由接受 JSON 的 3 种方法
【发布时间】:2012-09-27 19:30:33
【问题描述】:

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

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,

posting jquery .serializeArray(); output through ajax

2。与 (1) 相同,除了这一行:

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

Send post form data in json format via ajax with JQuery dynamically

3。与 (1) 相同,除了这一行:

data = form.serialize()

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

This may explain 为什么最好使用$.param,但这是一篇关于 jQuery 1.4 的旧帖子。

【问题讨论】:

    标签: ajax jquery


    【解决方案1】:

    这是来自 (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 年 12 月被外星人入侵,您应该尽快采取预防措施
    猜你喜欢
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多