首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

jQuery AJAX 點擊圖片刪除伺服器端檔案完整實作

     編輯:ASP.NET 基礎

前端頁面

<img src="Images/xiyangyang.jpg" alt="xiyangyang.jpg" />

<script src="jquery-1.4.4.js"></script>
<script>
$(function() {
    $("body img").click(function() {
        var fileName = $(this).attr("alt");
        $.ajax({
            url: "DeletePic.aspx",
            data: { picname: fileName },
            type: "POST",
            dataType: "json",
            success: function(resp) { alert(resp.result); },
            error: function(xhr) { alert("錯誤:" + xhr.status); }
        });
    });
});
</script>

後端 DeletePic.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (Request["picname"] == null) return;

    Response.Clear();
    Response.ContentType = "application/json";

    string result = "success";
    try
    {
        string physicalPath = Server.MapPath(@"~\Images\") + Request["picname"];
        if (File.Exists(physicalPath)) File.Delete(physicalPath);
        else result = "檔案不存在";
    }
    catch (Exception ex) { result = ex.Message; }

    Response.Write("{\"result\":\"" + result.Replace("\"", "\\\"") + "\"}");
    Response.End();
}

關鍵點

  • POST + data 物件:jQuery 自動序列化為 application/x-www-form-urlencoded,後端 Request["picname"] 取得。
  • Server.MapPath:解析虛擬路徑 ~/Images/ 為實體路徑,避免硬編碼。
  • Response.Clear/ContentType/End:確保純 JSON 輸出,無 HTML 混雜。
  • JSON 手工拼裝:簡單情況可接受;複雜物件建議 JavaScriptSerializer 或 Json.NET。
  • 安全性:實務必加驗證(檔名白名單、路徑遍歷防護 Path.GetFileName、權限檢查、CSRF Token)。

GET 版本(不建議刪除操作用 GET)

$.ajax({
    url: "DeletePic.aspx",
    data: "picname=" + encodeURIComponent(fileName),
    type: "GET",
    // ...
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved