【发布时间】:2016-09-07 05:03:56
【问题描述】:
每次我尝试这个都会得到 404。我在我的代码中找不到错误。我还有其他要删除的网络方法,它可以工作。我正在使用带有连接字符串 .NET 4.5 的 WebForm ADO.NET。
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ListarTiposLicencia()
{
TipoLicenciaBL objTipoLicencia = new TipoLicenciaBL();
//Return a DataTable from database with a stored procedure
DataTable dt = objTipoLicencia.DevolverListaTipoLicencia(String.Empty, String.Empty);
return DataTableToJSONWithJavaScriptSerializer(dt);
}
public static string DataTableToJSONWithJavaScriptSerializer(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
这是 ajax 调用:
$(document).ready(function () {
$("#obtenerLicencias").click(function () {
$.ajax({
type: "POST",
url: "CnfListaTipoLicencias.aspx/ListarTiposLicencia",
data: '{ }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
alert(JSON.parse(data));
},
failure: function (response) {
alert("Error");
},
error: function (error) {
alert("error");
}
});
});
});
编辑: 我试过这个,但它不起作用,我又得到 404:
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ListarTiposLicencia()
{
TipoLicenciaBL objTipoLicencia = new TipoLicenciaBL();
DataTable dt = objTipoLicencia.DevolverListaTipoLicencia(String.Empty, String.Empty);
string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
return json;
}
【问题讨论】:
-
构建您的 aspx 页面以确保其中没有任何错误。
-
去掉data属性看看
-
我在构建项目时没有收到任何编译错误。将DataTable转换为Json的方法需要一个DataTable并返回一个String
-
我试过了(删除数据属性),但它不起作用。
-
删除“数据”和“内容类型”属性。它们都与要发送到服务器的数据有关。由于您没有发送任何数据,因此您不需要它们。
标签: c# jquery asp.net json ajax