我正在尝试使用AJAX和C#从文件夹中删除图像。我创建了一个名为Delete.ashx的处理程序以删除图像。我还有一个AJAX函数来获取图像路径并将该路径传递给处理程序
在AJAX中,我有一个变量来获取存储在文本框中的路径(仅此刻)。我试图将路径传递给我的处理程序,但是问题是我试图传递数据路径的处理程序中的变量始终为空。
这是我的代码:
处理程序
public void ProcessRequest(HttpContext context)
{
string sFileName = context.Request["sFileName"]; //this variable is always empty
if (File.Exists(context.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context.Server.MapPath("~/images/" + sFileName));
context.Response.ContentType = "text/plain";
context.Response.Write("Image deleted Successfully!");
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Image Failed to Delete!");
}
}
AJAX
$(document).ready(function () {
$("#btnDelete").click(function () {
removeFile();
return false;
});
function removeFile() {
var FileName = $("#txtPath").val();
$.ajax({
url: 'Delete.ashx',
type: 'POST',
data: { 'sFileName': FileName},
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
});
请告知我如何将数据从AJAX传递到处理程序,以使变量不为空。谢谢。
答案 0 :(得分:2)
尝试从当前HttpContext获取上下文:
public void ProcessRequest(HttpContext context)
{
var context_= System.Web.HttpContext.Current;
string sFileName = context_.Request["sFileName"];
if (File.Exists(context_.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context_.Server.MapPath("~/images/" + sFileName));
context_.Response.ContentType = "text/plain";
context_.Response.Write("Image deleted Successfully!");
}
else
{
context_.Response.ContentType = "text/plain";
context_.Response.Write("Image Failed to Delete!");
}
}
或从ajax发送带有查询字符串的数据
modify ajax:
url: 'Delete.ashx?sFileName=blabla',
server side:
var sFileName= Request.Form["sFileName"];
答案 1 :(得分:0)
在Mennan的帮助下,我已完成以下工作并正在工作:
public void ProcessRequest(HttpContext context)
{
string sFileName = context.Request["sFileName"];
if (File.Exists(context.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context.Server.MapPath("~/images/" + sFileName));
context.Response.ContentType = "text/plain";
context.Response.Write("Image deleted Successfully!");
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Image Failed to Delete!");
}
}
function removeFile() {
var FileName = $("#txtPath").val();
$.ajax({
url: 'Delete.ashx?sFileName=' + FileName,
type: 'POST',
data: { 'sFileName': FileName},
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}