Html 5 FormData+Ajaxフォームデータ提出
3133 ワード
まずFormDataフォームについて
後にAjaxを構築させる
FormDataによるファイルアップロード
参照リンク:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
http://javascript.ruanyifeng.com/bom/ajax.html
http://hushicai.com/2014/03/29/html5-du-qu-ben-di-wen-jian.html
var formData = new FormData();
formData.append('name', 'zhangsan');
formData.append('age', 20);
formData.append('gender', 'M');
// , , session , form
formData.append('csrf', 'yty98db128swdx827dcd3jdxh');
<form id='registerform' name='user/register' action='user/register'>
<input type='text' name='username' value=' '>
<input type='email' name='email' value='[email protected]'>
<input type='number' name='birthDate' value='1940'>
<input type='submit' onclick='sendForm(this.form); return false;'>
</form>
var formData = new FormData(document.forms['registerform']);
formData.append('csrf', 'yty98db128swdx827dcd3jdxh');
後にAjaxを構築させる
function sendForm(formData) {
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function(e) { // ... };
//
xhr.onreadystatechange = function()
{
// , 4
var completed = 4;
if(xhr.readyState === completed)
{
if(xhr.status === 200)
{
//
}else{ //
}
}
};
xhr.send(formData);
}
FormDataによるファイルアップロード
function uploadFiles(url, files) {
var formData = new FormData();
for (var i = 0, file; file = files[i]; ++i)
{
formData.append(file.name, file);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function(e) { ... };
xhr.send(formData); // multipart/form-data }
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
uploadFiles('/server', this.files); },
false);
function upload(blobOrFile)
{
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', true);
xhr.onload = function(e) { ... }; // Listen to the upload progress.
var progressBar = document.querySelector('progress');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
}
};
xhr.send(blobOrFile);
}
upload(new Blob(['hello world'], {type: 'text/plain'}));
参照リンク:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
http://javascript.ruanyifeng.com/bom/ajax.html
http://hushicai.com/2014/03/29/html5-du-qu-ben-di-wen-jian.html