$ .post vs $ .ajax

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

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

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

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

我错过了什么?

它不起作用,因为在$.post方法中,您无法将请求的内容类型设置为application/json 。 因此,无法使用$.post调用ASP.NET PageMethod,因为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" }); 

这是另一种不使用ajax的方法。 它使用post并返回一个json对象。

 data = {}; data.standardBagProductId = standardBagProductId.trim(); $.post("StandardBag.aspx/RemoveProductFromStandardBag", data , function(response){ $(".reload").click(); },"json"); 

对于$ .post函数,第二个参数不应该在“”中。

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

尝试更改这样的post数据,

  {standardBagProductId: standardBagProductId.trim() }