簡體   English   中英

Ajax函數未從服務器接收響應

[英]Ajax function not receiving response from server

本質上,我正在使用一個上傳器( 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

應該發生的情況:單擊上載文件上的刪除鏈接后,客戶端將通過AjaxPOST發送到服務器。 然后,服務器將文件從磁盤上刪除,然后向客戶端發送一條消息,指出操作成功。

這是我第一次使用Ajax,怎么回事? 為什么不發送消息?

編輯:當我更改dataType: "json"進行test我會收到以下錯誤:

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

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

所以它稍微好一點,但我仍然不確定如何進行。

將您的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);
             }
         }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM