Jquery XMLHttpRequest not calling url


Jquery XMLHttpRequest not calling url

早上好

我到处寻找问题的答案,但运气不好。我想使用jquery,但尝试过"常规"Javascript,收效甚微。


我想上传一个文件(只是一个)通过ajax(异步)到一个php服务器,它将消耗文件(txt)。


该脚本不会调用php脚本,也不会上传文件。没有javascript错误,看起来脚本运行得很好。在chrome中,process.php不显示在网络部分,所以我不确定它是来自脚本还是我的php中的错误。


浏览器:Chrome Version 26.0.1410.64 m
Wamp服务器(php, mysql)
引导布局


指数:

<div class="span12" id="upload_form_div" style="display: block;">
    <form id="upload_form" enctype="multipart/form-data" class="upload_form">
        <fieldset>
            <legend>
                Please select a file to parse and merge with the database.
            </legend>
            <p>
                <label for="files">File:</label>
                <input type="file" class="text" id="files" name="file">
            </p>
            <p>
                <input type="button" value="Start Parse">
            </p>
        </fieldset>
    </form>
</div>

我包括jquery.js, app.js(用于上传的脚本文件)和bootstrap.min.js。只是觉得没有必要显示完整的html标记。

脚本文件:

$(function(){
$("#progressbar").hide();
});

function showProgress(evt) {
if (evt.lengthComputable) {
    var percentComplete = (evt.loaded / evt.total) * 100;
    $('#progressbar').progressbar("option", "value", percentComplete );
}
}
$(':button').click(function(){
var fileIn = $("#files")[0];
//Has any file been selected yet?
if (fileIn.files === undefined || fileIn.files.length == 0) {
    alert("Please select a file");
    return;
}
//We will upload only one file
var file = fileIn.files[0];
console.log(file);
//Show the progress bar
$("#progressbar").show();

$.ajax({
    url: 'process.php',  //server script to process data
    type: 'POST',
    data: file,
    contentType: file.type,
    processData: false,
    success: function(){
        $("#progressbar").hide();
    },
    error: function(){
        $("#progressbar").hide();
        alert("Failed");
        //alert(xhr.responseText);
    },
    xhr: function() {  // custom xhr
        myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){ // check if upload property exists
            //myXhr.upload.addEventListener('progress',showProgress, false); // for handling the progress of the upload
            //console.log($.ajaxSettings.xhr().upload);
            console.log(myXhr.responseText);
        } else {
            console.log("Upload progress is not supported.");
        }
        return myXhr;
    }
});
});

这是直接复制粘贴,所以我注释掉了一些疑难解答行。

PHP

<?php
set_error_handler("E_ALL");
$upload_directory = "files/";
move_uploaded_file($_FILES['file']['tmp_name'], $upload_directory . $_FILES['file']['name']);
?>

php文件将做更多,但我只是试图让文件在这一点上上传。

如果有人需要更多的信息,请告诉我,我会尽我所能提供信息。

对不起,您不能通过ajax请求上传文件。你需要有一点创意,在提交时使用隐藏框架。这通常包括创建一个新的隐藏表单,将文件控件克隆(或在IE中移动)到隐藏表单中,并将新表单附加到隐藏iframe上。iframe的post方法与您希望发送文件的URL挂钩。您可以通过创建/克隆文本框来包含变量,这些文本框将作为查询字符串的一部分发送到URL。
在客户端,在提交表单后创建一个计时器事件,它将检查javascript变量(在提交表单之前清除var)。在服务器端,通过响应对象发送javascript来设置客户端变量,这样你就知道文件上传完成了。这个过程相当复杂——特别是在IE中,你需要将文件控件移回原来的位置,并创建一个"虚拟"文件控件来将其存根。你可能想看看一些jQuery文件上传插件…下面是一段代码,让您开始使用iframe方法:

jQuery('#btn5Submit').click(function() {
    //create a temporary form with the fileboxes on it, then attach to the end of the html form (to avoid nested form tags)
    var wkForm = jQuery('<form id="tmpFileUpload" method="POST" action="filehandler.ashx" encType="multipart/form-data" target="uploadResult" class="ctlHidden"></form>');
    for (var i = 1; i < 4; i++) {
        var wkFile = jQuery('#file5Upload' + i);
        if (wkFile.val() != '' && wkFile.length != 0) {
            jQuery('<img src="Styles/Images/loading.gif" id="' + 'img5File' + i + '" />').insertAfter(wkFile);
            wkForm.append(wkFile);
        }
        else {
            //user did not provide a file, add a dummy file input to the temp form to maintain order
            wkForm.append('<input name="file5TUpload' + i + '" type="file"/>');
        }
    }
    jQuery('body').append(wkForm);
    jQuery('#tmpFileUpload').submit();
});
jQuery('.deleteFile').live('click', function() {
    editRow = jQuery(this).parent();
    var ddlog = jQuery('<div></div>');
    var btns = {};
    var gMsg = 'Are you sure you want to delete this file? (This will allow you to specify a new file, but the server file will not be replaced until "Send Files To Server" is pressed.)';
    ddlog.html(gMsg);
    var button1 = 'Delete File';
    var button2 = 'Cancel Deletion';
    btns[button1] = function() {
        var wkId = jQuery(editRow).attr('id');
        wkId = wkId.charAt(wkId.length - 1);
        jQuery('<input id="file5Upload' + wkId + '" name="file5Upload' + wkId + '" type="file" class="fileUpload" />').insertAfter(editRow);
        jQuery(editRow).remove();
        jQuery(this).dialog('close');
    };
    btns[button2] = function() {
        //Do not save changes, reset section control buttons, reset global var, reset initial_data values (Do not save changes)
        jQuery(this).dialog('close');
    };
    ddlog.dialog({ autoOpen: false, title: 'File Deletion Confirmation', resizable: false, modal: true, buttons: btns });
    ddlog.dialog('open');
});

我知道已经有一段时间了,但我已经找到了解决问题的方法。老实说,当我使用jQuery表单插件并注意到$_FILES[]实际上是与$_POST[]一起发送时,我偶然发现了这一点。它甚至不需要XMLHttpRequest。下面是我的代码。

Javascript

function saveForm(){
    $("#saveButton").button('loading');
    $("#MyForm").ajaxSubmit({
        url: 'save_script.php',
        type: 'post',
        success: function(responce){
            $("#saveButton").button('reset');
            rebuild_attachments();
        }
    });
};

注意,#saveButton是我点击保存表单的按钮的id, #MyForm是我提交的表单的id。我还使用bootstrap按钮将提交按钮更改为加载状态,以防止人们在上传大文件时多次单击。成功回调将保存按钮恢复到原始状态,以便他们可以再次提交表单。这也支持多个文件。

"rebuild_attachments()"是一个函数,我调用它使另一个。ajax请求重建一个div位于新的项目的表单中,如果有的话。我知道可能有更好的方法来处理这个问题,比如java脚本模板,但是这个方法对我来说是有效的。