我创建了一个简单的WebMethod来获取远程服务器上文件的大小。 JavaScript消息显示始终“失败”。我错过了什么?
TEST.ASPX.CS
[WebMethod]
public static string GetRecordingFileSize(string url)
{
try
{
WebRequest wr = (HttpWebRequest)WebRequest.Create(url);
var response = wr.GetResponse();
return response.ContentLength.ToString();
}
catch (WebException webException)
{
return webException.ToString();
}
}
Test.aspx文件
$.ajax({
type: "GET",
url: "TEST.aspx/GetRecordingFileSize",
data: "{ url : '" + $('#txtSoundFile').val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("okay");
$("#soundFile").attr("src", "Images/check.png");
},
error: function (xhr, status) {
alert("not okay");
$("#soundFile").attr("src", "Images/error.png");
}
});
答案 0 :(得分:0)
您可能需要使用POST
代替GET
。这个post就是一个很好的例子。
$.ajax({
type: "POST",
url: "TEST.aspx/GetRecordingFileSize",
data: "{ url : '" + $('#txtSoundFile').val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("okay");
$("#soundFile").attr("src", "Images/check.png");
},
error: function (xhr, status) {
alert("not okay");
$("#soundFile").attr("src", "Images/error.png");
}
});
如果您需要使用GET,那么您必须拥有[ScriptMethod(UseHttpGet = true)]
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string GetRecordingFileSize(string url)
{
//your code
}