问题描述
我有以下ajax请求,正在尝试将JSON对象发送到服务器:
I have the following ajax request in which I'm trying to send a JSON Object to the server:
function sendData(subscriptionJson) {
$.ajax({
type: "POST",
url: '@Url.Action("SubscribeSecurities", "Subscription")',
data: "{'subscriptions': subscriptionJson}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("success response: " + response.responseText);
alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
console.log("failure response: " + response.responseText);
alert(response.responseText);
},
error: function (response) {
console.log("error response: " + response.responseText);
alert(response.responseText);
}
});
}
基于此帖子中的最佳答案,我在数据"属性,但出现错误,提示无法识别"subscriptionJSON".我试过使用示例字符串进行测试,就像在帖子中所做的那样:data:"{'foo':'foovalue', 'bar':'barvalue'}",
,但是当控制器获取subscriptionJson对象的参数时,该参数为null.
Based on the top answer in this post I added quotes around the "data" attribute, but I'm getting an error saying that the "subscriptionJSON" isn't being recognized. I tried testing with a sample string as is done in the post: data: "{'foo':'foovalue', 'bar':'barvalue'}",
but when the controller gets the parameter of the subscriptionJson object it is null.
通过POST请求将JSON对象发送到ASP .NET MVC控制器的正式方法是什么?
推荐答案
您的问题是因为您没有发送有效的JSON.您需要将密钥用双引号引起来.另外,subscriptionJson
是代码中的文字字符串.您需要将其作为字符串变量.
Your issue is because you're not sending valid JSON. You need to wrap the keys in double quotes. Also, subscriptionJson
is a literal string in your code. You need it to be a string variable.
data: '{"subscriptions": ' + subscriptionJson + '}',
或者更好的是,只需为jQuery提供一个普通对象,然后让它为您编码值即可:
Or, even better, just provide a plain object to jQuery and let it encode the values for you:
data: { subscriptions: subscriptionJson },
这篇关于发送POST请求时无效的JSON原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!