【发布时间】:2014-10-09 06:50:06
【问题描述】:
我正在寻找某种方法将数据从 Polymer 表单字段传递到 REST API, 实际上,我正在使用 core-ajax 来执行此操作,但我认为执行此操作的方法有点繁重。
有什么标准的方法吗?
这是我的代码:
<template>
<section>
<file-input class="blue" id="file" extensions='[ "xls" ]' maxFiles="1">{{ FileInputLabel }}</file-input>
</section>
<section>
<paper-button raised class="blue" disabled?="{{ (! Validated) || (Submitted) }}" on-tap="{{ Submit }}">
<core-icon icon="send"></core-icon>
Process
</paper-button>
</section>
<paper-toast id="toast" text=""></paper-toast>
<core-ajax id="ajax" url="/import-pdi" method="POST" handleAs="json" response="{{ response }}" on-core-complete="{{ SubmitFinished }}"></core-ajax>
</template>
<script>
Polymer("import-pdi-form", {
Validated: false,
Submitted: false,
FileInputLabel: "SELECT",
ready: function () {
this.shadowRoot.querySelector("#file").addEventListener("change", function(event) {
var container = document.querySelector("import-pdi-form");
container.Validated = (event.detail.valid.length != 0);
if (event.detail.valid.length == 0) {
container.shadowRoot.querySelector("#toast").text = "Invalid Format";
container.shadowRoot.querySelector("#toast").show();
container.FileInputLabel = "SELECCIONA L'ARXIU";
}
else {
container.FileInputLabel = event.detail.valid[0].name;
var form_data = new FormData();
form_data.append("file", event.detail.valid[0], event.detail.valid[0].name);
container.shadowRoot.querySelector("#ajax").body = form_data;
container.shadowRoot.querySelector("#ajax").contentType = null;
}
});
},
Submit: function() {
if ((this.Validated) && (! this.Submitted)) {
this.Submitted = true;
this.shadowRoot.querySelector("#ajax").go();
}
},
SubmitFinished: function(event, detail, sender) {
if (detail.xhr.status == 200) {
this.shadowRoot.querySelector("#toast").text = JSON.parse(detail.xhr.response).message;
}
else {
this.shadowRoot.querySelector("#toast").text = "Server Error";
}
this.shadowRoot.querySelector("#toast").show();
this.FileInputLabel = "SELECCIONA L'ARXIU";
this.shadowRoot.querySelector("#file").reset();
this.Submitted = false;
}
});
</script>
【问题讨论】:
-
我注意到在很多地方你都在使用 this.shadowRoot.querySelector 来获取带有 id 的东西。您可以使用自动节点查找来更有效地做到这一点polymer-project.org/docs/polymer/…
-
@robdodson:感谢您的建议。我刚刚更改了 shadowRoot 并且一切运行良好。除此之外,我正在寻找将表单数据传递给服务器的最佳方式。现在我正在使用 core-ajax ,但它似乎有点重的解决方案。有什么标准吗?