在 google App Engine 上,我想使用 javascript(或 Ajax)发布表单,然后更新目标 div。该表单包含许多要传输的字段和文件。javascript 函数是从“Javascript: The Definite Guide”一书中复制而来的。我有两个问题:
- 在“form.html”中,如何为 postFormData() 函数准备“data”参数,以便可以传递所有字段和文件。
- 如何设计回调函数,使响应(即“form.html”)可以更新内容div?
谢谢你的帮助。
base.html:
...
<div id="content">
{% include "form.html" %}
</div>
Image:<br />
<img src="/file?entity_id={{entity.key}}" />
<br />
<script type="text/javascript">
function postFormData(url, data, callback) {
if (typeof FormData === "undefined")
throw new Error("FormData is not implemented");
var request = new XMLHttpRequest();
request.open("POST", url);
request.onreadystatechange = function() {
if (request.readystate === 4 && callback)
callback(request);
};
var formdata = new FormData();
for (var name in data) {
if (!data.hasOwnProperty(name)) continue;
var value = data[name];
if (typeof value === "function") continue;
formdata.append(name, value);
}
request.send(formdata);
}
</script>
...
表单.html
<form action="/form" method="POST" enctype="multipart/form-data">
name1: <input type="text" name="name" />{{ name1 }}<br /><br />
name2: <input type="text" name="name" />{{ name }}<br /><br />
...
file1: <input type="file" name="file" />{{ file1 }}<br /><br />
file2: <input type="file" name="file" />{{ file2 }}<br /><br />
...
<input type="submit" value="Submit" onclick="return postFormData('/form', howToPrepareData?, whatIsTheCallbackFunction?)" />
</form>