【问题标题】:jQuery post with form.serialize() receives null带有 form.serialize() 的 jQuery post 接收 null
【发布时间】:2013-05-10 12:21:02
【问题描述】:

当我使用 jQuery 以以下语法发布 HTML.Form 时:

$.post('<%: Url.Action("ActionName","ControllerName") %>',
             $("#FormName").serialize());

对象已正​​确发布到服务器,但如果我使用:

var reason = encodeURIComponent($("#FormName").serialize());
$.post('<%: Url.Action("ActionName","ControllerName") %>',
                        { reason: reason });

序列化对象为空,无论使用 encodeURIComponent 或不使用它,我都会得到相同的结果。 我需要向服务器发送更多的参数数据,这就是为什么我想使用第二种方法,但我无法正确发送序列化对象。

【问题讨论】:

  • 查看发布的数据(使用 Fiddler 或其他一些检查工具)会发现问题。 URI 编码单个数据点,而不是整个发布的序列化字符串。
  • 谢谢,有没有其他的编码方式?
  • 我很确定它已经编码的数据:stackoverflow.com/a/6653908/426894api.jquery.com/serializeThe .serialize() method creates a text string in standard URL-encoded notation.
  • 我检查了提琴手,正文中的区别是:reason=Type=1&Comments=&ID=15 vs Type=1&Comments=&ID=15 我的服务器端调用中的预期变量名称是“原因”。所以看起来序列化的字符串应该以某种方式装箱。

标签: jquery asp.net-mvc http-post


【解决方案1】:

它通过在发布数据时用 [] 将序列化字符串装箱来工作:

var reason = $("#FormName").serialize();
$.post('<%: Url.Action("ActionName","ControllerName") %>',
                    { reason: [reason] });

使用 HTTP Fiddler 检查时,帖子正文的不同之处在于:

var reason = $("#FormName").serialize();
$.post('<%: Url.Action("ActionName","ControllerName") %>',
                    { reason: reason });

body 标记包含如下内容:reason=Type=1&Comments=&ID=15,因此它无法区分变量实际包含的内容。通过使用 [] 将其装箱,body 标签现在包含:reason%5B%5D=Type%3D1%26Comments%3D%26ID%3D1 从而正确编码发布的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 2015-09-17
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2017-03-29
    • 2018-11-18
    相关资源
    最近更新 更多