[英]$.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: 我正在尝试使用$ .post方法来调用Web服务,我使用$ .ajax方法工作:
$.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方法时,它将无法工作:
$.post("StandardBag.aspx/RemoveProductFromStandardBag",
"{'standardBagProductId': '" + standardBagProductId.trim() + "' }",
function () { $((".reload")).click(); },
"json"
);
What am I missing? 我错过了什么?
It doesn't work because in your $.post
method you cannot set the content type of the request to application/json
. 它不起作用,因为在
$.post
方法中,您无法将请求的内容类型设置为application/json
。 So it is not possible to invoke an ASP.NET PageMethod using $.post
because an ASP.NET PageMethod requires a JSON request. 因此,无法使用
$.post
调用ASP.NET PageMethod,因为ASP.NET PageMethod需要JSON请求。 You will have to use $.ajax
. 你将不得不使用
$.ajax
。
I would just modify the data
in order to ensure that it is properly JSON encoded: 我只是修改
data
,以确保它是正确的JSON编码:
$.ajax({
type: "POST",
url: "StandardBag.aspx/RemoveProductFromStandardBag",
data: JSON.stringify({ standardBagProductId: standardBagProductId.trim() }),
success: function() {
$(".reload").click();
},
dataType: "json",
contentType: "application/json"
});
This is another way to do it not using ajax. 这是另一种不使用ajax的方法。 It uses post and returns a json object.
它使用post并返回一个json对象。
data = {};
data.standardBagProductId = standardBagProductId.trim();
$.post("StandardBag.aspx/RemoveProductFromStandardBag", data , function(response){
$(".reload").click();
},"json");
for $.post function second param should not be in "". 对于$ .post函数,第二个参数不应该在“”中。
$.post("StandardBag.aspx/RemoveProductFromStandardBag",
{'standardBagProductId': standardBagProductId.trim() },
function () { $(".reload").click(); },
"json"
);
尝试更改这样的帖子数据,
{standardBagProductId: standardBagProductId.trim() }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.