点击两次(有时),Ajax表单和图片上传立即失败

时间:2016-02-15 16:45:32

标签: javascript jquery ajax

function uploadFiles()
{
    submitting = true;

    var stocknum = _("stock_num").value;
    var name = _("product_name").value;
    var year = _("product_year").value
    var price = _("product_price").value;
    var category = _("category").value;
    var subcategory = _("subcategory").value;
    var details = _("product_description").value;
    var files = _("filesToUpload").files;

    //Create FormData object
    var formdata = new FormData();

    //Add stuff to it $_POST variables
    formdata.append('stocknum', stocknum);
    formdata.append('name', name);
    formdata.append('year', year);
    formdata.append('price', price);
    formdata.append('category', category);
    formdata.append('subcategory', subcategory);
    formdata.append('details', details);

    for (var i =0; i < files.length; i++){
        formdata.append('file[]', files[i]);    
    }
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "add_item_parser.php");
    ajax.send(formdata);

    function progressHandler(event)
    {
        _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
        var percent = (event.loaded / event.total) * 100;
        _("progressBar").value = Math.round(percent);
        _("status").innerHTML = Math.round(percent) + "% uploaded... please wait"; 
    }

    function completeHandler(event)
    {
        _("status").innerHTML = event.target.responseText;
        _("progressBar").value = 0;
        if(_("status").innerHTML == 100){
            window.setTimeout(function(){
            // Move to a new location or you can do something else
            window.location.href = "http://www.voltacltd.co.uk/storeadmin/product_list.php";

        }, 3000);
    }
}
function errorHandler(event)
{
    _("status").innerHTML = "Upload Failed!!!";
}
function abortHandler(event)
{
    _("status").innerHTML = "Cancelled by user!!!";
}

1 个答案:

答案 0 :(得分:0)

刚想通了。 那是:

<input id="addItemButton" type="submit" value="Add Item"     onClick="uploadFiles(this)">

我将其更改为键入=&#34;按钮&#34;

<input id="addItemButton" type="button" value="Add Item" onClick="uploadFiles(this)">

这停止了导致Ajax失败的页面刷新。 谢谢你帮助杰森