前端頁面
<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",
// ...
});