由于某种原因,这个AJAX程序不接受我的json对象。
我有一个由registerdb访问的mdf文件,我确信它是正确的。
它有3列:ids,用户名和密码填充数据。
任何帮助都将不胜感激。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%= btn.ClientID %>").click(function () {
var User = $("#<%= txtuser.ClientID %>").val();
var Pass = $("#<%= txtpass.ClientID %>").val();
var data = "{ Username: " + User + ", Password: " + Pass + " }"
var json1 = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Login",
data: json1,
dataType: "json",
success: function (result) {
$("#<%= txtid.ClientID %>").val(result.d);
},
error: function (Msg) {
$("#<%= lblError.ClientID %>").text('failed:' + Msg.status + ':' + Msg.responseText);
}
}); return false;
});
});
</script>
Default.aspx.cs
[System.Web.Services.WebMethod]
public static string Login(string Username,string Password)
{
string ids="";
string connStr = ConfigurationManager.ConnectionStrings["registerdb"].ConnectionString;
string cmdStr = "SELECT [ids] FROM [register] WHERE [username]=@username AND [password]=@password;";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("@username", Username);
cmd.Parameters.AddWithValue("@password", Password);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
ids = rdr[0].ToString();
}
}
if (ids == "") { ids = "No Match"; };
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return ids;
}
错误代码:
失败:500:{“消息”:“无法将类型为\ u0027System.String \ u0027的对象转换为类型\ u0027System.Collections.Generic.IDictionary`2 [System.String,System.Object] \ u0027”,“在System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain的System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o,Type type,JavaScriptSerializer serializer,Boolean throwOnError,Object \ u0026 convertedObject)\ r \ n的StackTrace“:” (Object o,Type type,JavaScriptSerializer serializer,Boolean throwOnError,Object \ u0026 convertedObject)\ r \ n在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer,String input,Type type,Int32 depthLimit)\ r \在系统上的System.Web.Script.Serialization.JavaScriptSerializer.Deserialize [T](字符串输入)\ r \ n处于System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext上下文,JavaScriptSerializer序列化程序)\ r \ n。 Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodDa ta methodData,HttpContext context)\ r \ n在System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)“,”ExceptionType“:”System.InvalidOperationException“}
答案 0 :(得分:0)
您的问题是您传入JSON.stringify
的数据是字符串,而不是JSON对象。这就是你应该这样做的方式:
var data = {Username:User, Password:Pass};
var json1 = JSON.stringify(data);