jQuery的阿贾克斯'后'电话 [英] jquery ajax 'post' call
问题描述
我是新来的jQuery和Ajax,和我有一个后的麻烦。
I am new to jQuery and Ajax, and am having trouble with a 'post'.
我使用jQuery的阿贾克斯'后'调用的数据保存到数据库中。当我尝试保存数据时,它把空我的C#方法。 jQuery的是这样的:
I am using a jQuery Ajax 'post' call to save data to a DB. When I attempt to save the data, it passes null to my C# method. The jQuery looks like this:
function saveInfo(id) {
var userID = id;
var userEmail = $('.userEmail').val();
var userName = $('.userName').val();
var dataJSON = {"userID": userID, "userEmail": userEmail, "userName": userName};
$.ajax({
type: 'POST',
url: '../../Services/AjaxServices.svc/SaveUser',
data:JSON.stringify(dataJSON),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
return false;
}`
.userEmail和.userName是类引用到输入字段。在C#code是这样的:
.userEmail and .userName are class references to input fields. The C# code looks like this:
[ServiceContract(Namespace = "http://testUsePage.com")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class AjaxServices
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
public void SaveUser(User user)
{
//code here handles save
}
}
我有一个断点SaveUser'方法内设置,并通过用户对象总是空。谢谢!
I have a breakpoint set inside the 'SaveUser' method, and the User object passed is always null. Thanks!
编辑:我切换后到GET两个Ajax调用和WebInvoke属性。传递一个参数({用户名:用户ID})的方法签名(公共无效SaveUser(字符串用户名))达到断点,并通过与不例外的用户名。切换回后立即导致内部服务器错误。
I switched the 'POST' to 'GET' in both the ajax call and WebInvoke attribute. Passing one parameter ( {"UserID": UserID} ) to the method with the signature ( public void SaveUser(string UserID) ) reaches the breakpoint, and passes the UserID with no exception. Switching it back to a post immediately causes an internal server error.
推荐答案
您应该把您的用户数据是这样的:
You should send your user data in this way:
{用户:{用户ID:1,...}}
{ user : { userID : 1, ... } }
由于您使用的是wrappedrequest。在你的JSON第一要素应该是你的参数名称。
since you are using wrappedrequest. First element in your json should be your parametername.
你的code,其余似乎确定。您应该使用字符串化。
The rest of your code seems ok. You should use stringify.
这篇关于jQuery的阿贾克斯'后'电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!