問題描述
我想在 JavaScript 中使用 XMLHttpRequest 來發布一個包含文件類型輸入元素的表單,這樣我就可以避免頁面刷新并返回有用的 XML.
I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back.
我可以在不刷新頁面的情況下提交表單,使用 JavaScript 將表單上的目標屬性設置為 MSIE 的 iframe 或 Mozilla 的對象,但這有兩個問題.小問題是目標不符合 W3C(這就是我在 JavaScript 中設置它的原因,而不是在 XHTML 中).主要問題是 onload 事件不會觸發,至少在 OS X Leopard 上的 Mozilla 上不會.此外,XMLHttpRequest 會做出更漂亮的響應代碼,因為返回的數據可以是 XML,而不是像 iframe 那樣僅限于 XHTML.
I can submit the form without page refresh, using JavaScript to set the target attribute on the form to an iframe for MSIE or an object for Mozilla, but this has two problems. The minor problem is that target is not W3C compliant (which is why I set it in JavaScript, not in XHTML). The major problem is that the onload event doesn't fire, at least not on Mozilla on OS X Leopard. Besides, XMLHttpRequest would make for prettier response code because the returned data could be XML, not confined to XHTML as is the case with iframe.
提交表單會產生如下所示的 HTTP:
Submitting the form results in HTTP that looks like:
Content-Type: multipart/form-data;boundary=<boundary string>
Content-Length: <length>
--<boundary string>
Content-Disposition: form-data, name="<input element name>"
<input element value>
--<boundary string>
Content-Disposition: form-data, name=<input element name>"; filename="<input element value>"
Content-Type: application/octet-stream
<element body>
如何獲取 XMLHttpRequest 對象的 send 方法來復制上述 HTTP 流?
How do I get the XMLHttpRequest object's send method to duplicate the above HTTP stream?
推薦答案
您可以自己構造 'multipart/form-data' 請求(在 http://www.faqs.org/rfcs/rfc2388.html) 然后使用 send
方法(即 xhr.send(your-multipart-form-data)).同樣,但更簡單的是,在 Firefox 4+(也在 Chrome 5+ 和 Safari 5+)中,您可以使用 FormData 接口,有助于構建此類請求.send
方法適用于文本內容,但如果要發送圖像等二進制數據,可以借助已經開始的 sendAsBinary
方法來完成使用 Firefox 3.0.關于如何通過XMLHttpRequest
發送文件的詳細信息,請參考http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html.
You can construct the 'multipart/form-data' request yourself (read more about it at http://www.faqs.org/rfcs/rfc2388.html) and then use the send
method (ie. xhr.send(your-multipart-form-data)). Similarly, but easier, in Firefox 4+ (also in Chrome 5+ and Safari 5+) you can use the FormData interface that helps to construct such requests. The send
method is good for text content but if you want to send binary data such as images, you can do it with the help of the sendAsBinary
method that has been around starting with Firefox 3.0. For details on how to send files via XMLHttpRequest
, please refer to http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html.
這篇關于XMLHttpRequest POST 多部分/表單數據的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!