我正在尝试通过ajax发送和接收数据。但它没有用。我不知道自己在代码上犯了什么错误。
这是我的代码:
我尝试了以下代码
Jquery AJAX代码
$.ajax({
type: 'POST',
url: 'AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=1&ReportName=TotalSales',
contentType: 'application/json; charset=utf-8',
data: 'json',
dataType: 'json', //If I remove this line it's call AjaxSucceeded but result is undefined
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("Error");
alert(result.status + ' ' + result.statusText);
}
它alert1 =
Error
和alert2 =200 ok
服务器端代码
public class GetResult
{
public string removedReportName { get; set; }
public string removedColumnNames { get; set; }
public string removedFilterNames { get; set; }
}
public partial class AjaxSecurity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string securityLevelOrUser = Request["securityLevelOrUser"].ToString();
if (securityLevelOrUser.Equals("SecurityLevel"))
{
string jsonString = js.Serialize(getResultBySecurityLevel(Request["SecurityKey"], Request["ReportName"]));
Response.Write(jsonString);
}
else
{
}
}
private GetResult getResultBySecurityLevel(string securityLevel,string reportName)
{
GetResult getResult = new GetResult();
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ReportHide,RColumnName,RFilterName FROM SecurityLevelDetails WHERE SecurityLevel=@SecurityLevel and ReportName=@ReportName";
cmd.Parameters.AddWithValue("@ReportName", reportName);
cmd.Parameters.AddWithValue("@SecurityLevel", securityLevel);
con.Open();
SqlDataReader rd=cmd.ExecuteReader();
while(rd.Read())
{
getResult.removedReportName = rd["ReportHide"].ToString();
getResult.removedColumnNames = rd["RColumnName"].ToString();
getResult.removedFilterNames = rd["RFilterName"].ToString();
}
}
return getResult;
}
}
我还有一个疑问。 当我使用asp.net google关于Ajax时,其中一些人使用 webservice,webmethod,服务器端代码。
我们可以在哪里实施webmethod?在哪种场景基础上我们可以使用web方法?
更新
以前的错误已修复
dataType:' json',//如果我删除此行,则调用AjaxSucceeded但结果未定义