【发布时间】:2017-03-29 12:55:59
【问题描述】:
我想向服务器传递一些值,它必须返回一个字符串。
jQuery 版本
<script src="js/jquery-3.1.1.js"></script>
这是我的代码:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx 代码
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=@UserFileName and ReportName=@ReportName";
cmd.Parameters.AddWithValue("@UserFileName", fileName);
cmd.Parameters.AddWithValue("@ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
错误消息
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
消息:“尝试使用 GET 请求调用方法 'getFileExistOrNot',这是不允许的。”
StackTrace:" 在 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) ↵ 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)"。
我认为这个错误发生在服务器端。但我不知道那是什么
更新
错误消息:“无效的 Web 服务调用,缺少参数值:'fileName'。”
【问题讨论】:
-
将 [ScriptMethod(UseHttpGet=true)] 添加到 [WebMethod] 正下方的 C# 方法中
-
为什么是负分。告诉我正确的原因。
标签: javascript jquery json ajax webmethod