简体   繁体   English

jquery ajax'post'电话

[英]jquery ajax 'post' call

I am new to jQuery and Ajax, and am having trouble with a 'post'. 我是jQuery和Ajax的新手,我遇到了“帖子”的问题。

I am using a jQuery Ajax 'post' call to save data to a DB. 我正在使用jQuery Ajax'post'调用将数据保存到数据库。 When I attempt to save the data, it passes null to my C# method. 当我尝试保存数据时,它将null传递给我的C#方法。 The jQuery looks like this: jQuery看起来像这样:

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 and .userName are class references to input fields. .userEmail和.userName是对输入字段的类引用。 The C# code looks like this: C#代码如下所示:

[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
    }
}

I have a breakpoint set inside the 'SaveUser' method, and the User object passed is always null. 我在'SaveUser'方法中设置了断点,并且传递的User对象始终为null。 Thanks! 谢谢!

EDIT: I switched the 'POST' to 'GET' in both the ajax call and WebInvoke attribute. 编辑:我在ajax调用和WebInvoke属性中将'POST'切换为'GET'。 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. 将一个参数({“UserID”:UserID})传递给带有签名的方法(public void SaveUser(string UserID))到达断点,并传递UserID,没有异常。 Switching it back to a post immediately causes an internal server error. 将其切换回帖子会立即导致内部服务器错误。

You should send your user data in this way: 您应该以这种方式发送您的用户数据:

{ user : { userID : 1, ... } } {user:{userID:1,...}}

since you are using wrappedrequest. 因为你正在使用wrappedrequest。 First element in your json should be your parametername. 你的json中的第一个元素应该是你的参数。

The rest of your code seems ok. 其余代码似乎没问题。 You should use stringify. 你应该使用stringify。

You dont need to use json for something so small. 你不需要使用json这么小的东西。 try this 试试这个

function saveInfo(id) {
    var userID = id; 
    var userEmail = $('.userEmail').val();
    var userName  = $('.userName').val();
        $.ajax({type: 'POST',
            url: '../../Services/AjaxServices.svc/SaveUser/?userID='+userID+"&userEmail="+userEmail+"&userName="+userName,
        });
    return false;
}

You aren't setting RequestFormat property of the WebInvoke attribute to json. 您没有将WebInvoke属性的RequestFormat属性设置为json。

Also in the $.ajax call send data: dataJSON without the JSON.stringify call. 同样在$ .ajax调用中发送数据:dataJSON而没有JSON.stringify调用。

If this fails try the following which will post form encoded information(the default) not json. 如果此操作失败,请尝试以下方式发布表单编码信息(默认值)而不是json。 client side 客户端

$.post('../../Services/AjaxServices.svc/SaveUser',
 {"userId": userID, "userEmail": userEmail, "userName": userName}
);

server side 服务器端

[WebInvoke(Method = "POST", UriTemplate = "SaveUser?userId={userId}&userEmail={userEmail}&userName={userName}")]
public void SaveUser(string userId, string userEmail, string userName)

Have you tried opening the Net tab in Firefox's Firebug and profiling your call to see what is the actual data being posted to the web-service? 您是否尝试在Firefox的Firebug中打开Net选项卡并分析您的调用以查看发布到Web服务的实际数据是什么? Try that, if the data in there is empty then you know there's something in your Javascript that's wrong, then try to debug your Javascript. 试试看,如果那里的数据是空的,那么你知道你的Javascript中有些东西是错的,然后尝试调试你的Javascript。

But the problem is probably that your web-service method signature is expecting a User object as a parameter but you are passing in a bunch of literal parameters. 但问题可能是您的Web服务方法签名期望将User对象作为参数,但您传递了一堆文字参数。 You can change your method signature to something like this and it might work: 您可以将方法签名更改为类似的内容,它可能会起作用:

public void SaveUser(string userID, string userEmail, string userName)

I read your comments, try this: 我看了你的评论,试试这个:

No stringify on your JSON object in client-side script 客户端脚本中的JSON对象没有字符串化

public class AjaxServices
{
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle=WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    public void SaveUser(string userID, string userEmail, string userName)
    {
        //code here handles save
    }
}

Simply: the data attribute of $.ajax() is a map (object) of data not a string of data. 简单地说: $.ajax()data属性是data的映射(对象),而不是数据字符串。 Don't stringify the object before sending it: 在发送之前不要对对象进行字符串化:

var dataJSON = {"userID": userID, "userEmail": userEmail, "userName": userName};

$.ajax({
    type: 'POST',
    url: '../../Services/AjaxServices.svc/SaveUser',
    data: dataJSON,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM