2013-06-18 34 views
0

我想通過jQuery和ajax將數據從textBoxes輸入到restful服務。但我無法做到。將數據從HTML中的textBox發佈到使用jQuery的Restful服務AJAX

這裏是我的HTML代碼:

<!DOCTYPE html> 
&nbsp; 
<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

嘗試序列化表單:

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); 
    } 
}); 
+0

我試過了但不工作:/ –

0

嘗試登錄方法返回以下

return Json(new { Id = oUser.Id, Username = oUser.Username }); 

然後在成功的功能

success: function (result) { 
     alert("success"); 

     alert(result.Id); 
} 

課程類型,並且必須是在POST Ajax調用

+0

登錄方法工作正常。我試圖從Windows Phone撥打它,它對我來說工作得很好。 –

1

我想你能使你的代碼中的錯誤。你的寫作服務是「發佈」,你使用「GET」來調用。所以請改變這一點。

[WebGet(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 
相關問題