Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

asp.net - $.post vs $.ajax

I'm trying to use the $.post method to call a web service, I've got it working using the $.ajax method:

$.ajax({
    type: "POST",
    url: "StandardBag.aspx/RemoveProductFromStandardBag",
    data: "{'standardBagProductId': '" + standardBagProductId.trim() + "' }",
    success: function(){
                 $((".reload")).click();
             },
    dataType: "json",
    contentType: "application/json"
});

But when I move the same method into the $.post method, it will not work:

$.post("StandardBag.aspx/RemoveProductFromStandardBag",
    "{'standardBagProductId': '" + standardBagProductId.trim() + "' }",
    function () { $((".reload")).click(); },
    "json"
);

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't work because in your $.post method you cannot set the content type of the request to application/json. So it is not possible to invoke an ASP.NET PageMethod using $.post because an ASP.NET PageMethod requires a JSON request. You will have to use $.ajax.

I would just modify the data in order to ensure that it is properly JSON encoded:

$.ajax({
    type: "POST",
    url: "StandardBag.aspx/RemoveProductFromStandardBag",
    data: JSON.stringify({ standardBagProductId: standardBagProductId.trim() }),
    success: function() {
        $(".reload").click();
    },
    dataType: "json",
    contentType: "application/json"
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...