第一个问题
我为另一位编码员处理代码。
我必须正确检查 cron 表达式,并且我可以更改程序中的许多行代码。我从表单中获取参数并尝试将此数据发送到 Controller MVC
var outl = document.getElementById('Frequency').value;
var tmp = checkValid(outl);
和
function checkValid(checkExpression)
{
var tmp = JSON.stringify(checkExpression);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: String,
type: 'POST',
url: '/Service/isValid',
data: tmp,
success: function (isvalid)
{
return isvalid;
}
});
console.log(tmp);
}
MVC 中的 Controller 如下所示:
public JsonResult isValid(string dataFromJson)
{
Options options = new Options()
{
ThrowExceptionOnParseError = true,
Use24HourTimeFormat = true,
};
try
{
ExpressionDescriptor ceh = new ExpressionDescriptor(dataFromJson, options);
string description = ceh.GetDescription(DescriptionTypeEnum.FULL);
return Json(true);
}
catch (FormatException)
{
return Json(false);
}
}
参数dataFromJson
总是为空。为什么?真的,我不知道我错在哪里。
第二部分
在 Controller 中我返回 JSON - 这是个好主意吗?如何在 Ajax 中从该 Controller 获取响应
最佳答案
按如下方式更改 ajax
数据。
function checkValid(checkExpression)
{
var tmp = JSON.stringify({dataFromJson : checkExpression});
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: "json",
type: 'POST',
url: '/Service/isValid',
data: tmp,
success: function (isvalid)
{
return isvalid;
}
});
console.log(tmp);
}
在上面,我改变了 var tmp = JSON.stringify({dataFromJson : checkExpression});
这个,现在它可以在服务器端绑定(bind)了。如果您希望服务器响应返回 json,请将 dataType
更改为 json
。
关于第二部分,根据您的要求,您可以根据需要使用 Content
或 Json
。
关于javascript - JSON发送的数据始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30454919/