我试图通过jQuery和ajax将数据从textBoxes的输入值发布到restful服务。但我无法做到这一点。
这是我的HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="LoginHtml.js">
</script>
</head>
<body>
<div id="registration">
<h2>Login Account</h2>
<form id="registerUserForm">
<fieldset>
<p>
<input id="txtUserName" type="text" required="required" autofocus="true" placeholder="User Name" />
</p>
<p>
<input id="txtPassword" type="password" required="required" placeholder="Password" />
</p>
<p>
<input type="button" id="submitForm" autofocus="true" /><br>
<input type="button" value="Login" onclick="Call()" ></input>
</p>
</fieldset>
</form>
</div>
</body>
</html>
这是我的javascript代码:
function Call() {
jQuery.support.cors = true;
var data = {};
data.uid = document.getElementById('txtUserName');
data.pwd = document.getElementById('txtPassword');
$.ajax({
data: jQuery.toJSON(data),
dataType: "json",
url: "http://:xxxxxx:8080/Service1/Login",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (result) {alert("success");
alert(result.d);}
error: function OnError(request, result, error) {
alert(result);
}
});
这是我的服务代码:
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public UserProfile Login(string uid, string pwd)
{
UserProfile oUser = null;
//UserDao userDao;
using (UserProfileDataContext db = new UserProfileDataContext())
{
var u = db.Users.FirstOrDefault(o => o.Username == uid && o.Password == pwd);
if (u != null)
{
oUser = new UserProfile();
oUser.Id = u.Id;
oUser.Username = u.Username;
oUser.Password = u.Password;
oUser.Email = u.Email;
}
}
return oUser;
}
告诉我哪里错了。
答案 0 :(得分:1)
我认为你在代码中犯了错误。你的写作服务是“发布”,你用“GET”来调用它。所以请改变这个。
[WebGet(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
答案 1 :(得分:0)
尝试序列化表单:
var data = $("#registerUserForm").serialize();
将类型更改为POST而不是GET
所以......
$.ajax({
data: data,
url: "http://:xxxxxx:8080/Service1/Login",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success");
alert(result.d);
}
error: function OnError(request, result, error) {
alert(result);
}
});
答案 2 :(得分:0)
尝试在Login方法中返回以下内容
return Json(new { Id = oUser.Id, Username = oUser.Username });
然后在成功功能
success: function (result) {
alert("success");
alert(result.Id);
}
当然,类型必须是ajax调用中的POST