我有一种情况,我正在构建要动态发布的json数据。所以我在for循环中创建它,然后尝试使用$ .ajax命令,但是在服务器端,该模型为null。如果我像往常一样对数据部分进行硬编码,则可以正常工作。我用一个简单的模型尝试了相同的过程,只是为了检查是否发生相同的情况。
所以这有效:
$.ajax({
url: '@Url.Action("SetupQuestions", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: {SharedSecret: 'Bob'},
success: function (data, status, xhr) {
$('#divMFAQuestion').html(data).fadeIn('slow');
},
error: function (xhr, status, error) {
alert("MFA Challenge Error (b): " + error);
}
});
但这不是:
var datastring = '{SharedSecret: Bob}';
$.ajax({
url: '@Url.Action("SetupQuestions", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
processData: false,
data: JSON.stringify(datastring),
success: function (data, status, xhr) {
$('#divMFAQuestion').html(data).fadeIn('slow');
},
error: function (xhr, status, error) {
alert("MFA Challenge Error (b): " + error);
}
});
也没有:
var datastring = 'SharedSecret: Bob';
有什么想法吗?
您对整个JSON数据结构都有引号:
var datastring = '{SharedSecret: Bob}';
JSON.stringify
期望使用JSON结构,因此引号应仅在字符串部分周围JSON.stringify
起作用:
var datastring = {SharedSecret: 'Bob'};
但是,您的AJAX调用不起作用的原因是该data
参数接受JSON数据结构。JSON.stringify
会将其序列化为字符串,这data
是不期望的。因此,您只需要通过不datastring
带的定值JSON.stringify
。
data: datastring
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句