0

I am trying to add the page_id and page_slug to the loop so that when an image is uploaded the details page id and slug go to.

Normally I would use this: data: { page_id: page_id, page_slug: page_slug } But formData is there..

(function () {
var input = document.getElementById("images"), 
    formdata = false;
var page_id = $('#page_id').val();
var page_slug = $('#page_slug').val();


function showUploadedItem (source) {
    var list = document.getElementById("image-list"),
        li   = document.createElement("li"),
        img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
    list.appendChild(li);
}   

if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
}

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Uploading . . ."
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];

        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("images[]", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: "admin/pages/upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                document.getElementById("response").innerHTML = res; 
            }
        });
    }
}, false);
}());
4

1 回答 1

2

我不认为您可以直接在函数内部$.ajax甚至$.ajaxSetup函数中操作 FormData 对象,因此在以下代码块中添加两个调用 append 应该包含所需的参数。

if (window.FormData) {
  formdata = new FormData();
  formdata.append('page_id', page_id);
  formdata.append('page_slug', page_slug);
  document.getElementById("btn").style.display = "none";
}

page_idand值是唯一的page_slug,因此不需要在循环中附加;创建 FormData 对象后只需一次。

有关更多示例,另请参阅使用 FormData 对象

于 2012-07-17T13:48:49.997 回答