【问题标题】:Post json object with iron-ajax as application/x-www-form-urlencoded将带有 iron-ajax 的 json 对象发布为 application/x-www-form-urlencoded
【发布时间】:2015-12-21 18:13:00
【问题描述】:

在我的基于 Polymer 的应用程序中,我想使用精美的 JavaScript 模型绑定到输入元素。

模型的 POST 到我的 Spring 控制器,但是我想作为经典表单数据执行,以便我可以利用 Spring SessionAttributes。

我这样设置iron-ajax

<iron-ajax id="saveMailing"
    method="POST"
    url="/api/mailing"
    content-type="application/x-www-form-urlencoded"
    on-response="mailingSaved">
</iron-ajax>

我有一个 JavaScript 方法,在单击按钮时执行请求:

saveDraft: function() {
    this.$.saveMailing.body = this.mailing;
    this.$.saveMailing.generateRequest();
}

this.mailing 是一个 JSON 对象。 不是 FormData()。

结果是我在 iron-request.html:421 中收到 JavaScript 错误“Cannot read property toString of null”

有没有可能做我想做的事?我的意思是传递 iron-ajax 一个 JSON-Object 并期望它将其转换为 FormData。还是我没有正确使用iron-ajax

【问题讨论】:

  • 你还没有告诉我们this.mailing 来自哪里。它看起来像 Iron-ajax 认为它是空的
  • 我确实使用了iron-ajaxnew FormData() 样式数据集。一旦你在上面添加了this.mailing 定义,肯定会有一些愚蠢或小东西在逃避你。
  • this.mailing 是一个 json 对象,它不为空。
  • 我相信真正的问题是:iron-ajax 可以将 JavaScript-Object 转换为 FormData() 吗?

标签: javascript json spring-mvc polymer


【解决方案1】:

假设您确定this.mailing 不是null,您需要先对其进行字符串化:

this.$.saveMailing.body = JSON.stringify(this.mailing);

【讨论】:

  • 我已经尝试过了,现在又重新尝试了......但它也不起作用。
  • 事实上,它执行 POST,但不是使用表单数据,而是使用 JSON 字符串。所以 JSON.stringify() 有效,但不会发生向表单数据的转换。
  • 您在服务器端使用 PHP 吗?我发现自己不得不使用$_POST = json_decode(file_get_contents('php://input'), true);
  • 我使用 Spring Controller,也就是 Java,带有 ModelAttribute 注释,将表单数据直接解析为对象。
猜你喜欢
  • 2013-09-25
  • 2017-09-11
  • 2019-07-28
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
相关资源
最近更新 更多