$ .post vs $ .ajax

Mar*_*ffx 16 asp.net ajax jquery asp.net-ajax

我正在尝试使用$ .post方法来调用Web服务,我使用$ .ajax方法工作:

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

但是当我将相同的方法移动到$ .post方法时,它将无法工作:

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

我错过了什么?

Dar*_*rov 24

它不起作用,因为在您的$.post方法中,您无法将请求的内容类型设置为application/json.因此,无法使用ASP.NET PageMethod来调用ASP.NET PageMethod,$.post因为ASP.NET PageMethod需要JSON请求.你将不得不使用$.ajax.

我只是修改它data,以确保它是正确的JSON编码:

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