Ajax函数没有从服务器接收响应

时间:2015-05-29 13:11:18

标签: javascript jquery asp.net ajax vb.net

基本上我正在使用上传器(dropzone.js)并将其合并到我的网站中。将文件添加到服务器工作正常,但是我无法删除它们。我的JavaScript:

$(document).ready(function () {
    Dropzone.autoDiscover = true;
    $("#dZUpload").dropzone({
        url: "uploadHandler.ashx",
        addRemoveLinks: true,
        success: function (file, response) {
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded: " + file.name);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
        },
        init: function () {
            var dZUpload = this;
            this.on("removedfile", function (file) {
                $.ajax({
                    type: "POST",
                    url: "uploadHandler.ashx/DeleteFile",
                    data: { filename: file.name },
                    dataType: "json",
                    success: function (repsonse) {
                        if (data == "success") {
                            alert("Successfully deleted.");
                            this.removeFile(file);
                        }
                        else {
                            alert("Error deleting file.");
                            this.removeFile(file);
                        }
                    }
                });
            });
        }

    });
});

这是我服务器端处理程序上deleteFile函数的代码:

    <System.Web.Services.WebMethod()> _
Public Function DeleteFile(filename As String) As String
    Try
        Dim Yes As String = "success"
        System.IO.File.Delete(Path.Combine(HttpContext.Current.Server.MapPath("~/serverFiles/"), filename))
        Return Yes
    Catch ex As Exception
        Dim No As String = "failure"
        Return No
    End Try
End Function

应该发生什么:当在上传的文件上单击删除链接时,客户端会向服务器发送POSTAjax。服务器除了从磁盘上删除文件,并向客户端发送一条消息说它成功了。

这是我第一次使用Ajax,发生了什么?为什么不发送消息?

修改:当我将dataType: "json"更改为test时,我发现以下错误:

Uncaught ReferenceError: data is not defined
$.ajax.success @ fileUploader.aspx:31

第31行是:if (data == "success") {

所以它好一点,但我仍然不确定如何继续。

1 个答案:

答案 0 :(得分:0)

将您的Web方法声明为共享(静态),例如

    Public Shared Function DeleteFile(filename As String) As String

然后将您的AJAX调用修改为:

    var data = { filename: file.name }
    $.ajax({
         method: "POST",
         url: "uploadHandler.ashx/DeleteFile",
         data: JSON.stringify(data),
         dataType: "json",
         contentType: "application/json; charset=utf-8",
         success: function (repsonse) {
             if (data == "success") {
                 alert("Successfully deleted.");
                 this.removeFile(file);
             }
             else {
                 alert("Error deleting file.");
                 this.removeFile(file);
             }
         }
    });