MVC:虽然从控制器检索通过JSON对象看来,JavaScript错误 [英] MVC: While retrieving the passed Json object from controller in view, JavaScript error
问题描述
我传递一些字符串消息作为JSON对象在视图中。
I'm passing some string messages as Json object in view.
public ActionResult SomeAction(someObject object)
{
.....
.....
if (check1)
{
return Json(new { error = Resource.someMessage1},JsonRequestBehavior.AllowGet);
}
if(check2)
{
return Json(new { error = Resource.someMessage2}, JsonRequestBehavior.AllowGet);
}
//some stuffs
return Json(new {success = "success"}, JsonRequestBehavior.AllowGet);
}
我想从我的观点检索控制器和警报传递的消息
I want to retrieve the messages passed from controller and alert from My view
鉴于我有一些javascript
in view I have some javascript
function done(data) {
alert("hello");
var message = JSON.parse(data);
alert(message);
if (message["error"] != undefined) {
alert(message["error"]);
} else {
//do some stuff
}
};
我所期待的是,如果从控制器传递的信息是错误类型,然后我会得到的信息提示。
what I was expecting is if passed message from controller is type error then I would get alert with the message.
行警报(你好);
但没有警告之后。
我得到了控制台错误
The line alert("hello");
but there is no alert after that.
I get error in console
我是不是做错了什么?
推荐答案
变量类型被检测为JSON对象。
the variable type is detected as json object.
var x = {"error":"somemessage"};
alert(x.error)
变量被检测为字符串在这里。
The variable is detected as String here.
VAR X = JSON.parse('{错误:somemessage}');
警报(x.error)
如果你注意到,不同的是#1开始与{(花括号),而#2开始使用'(撇号)
If you notice, the difference is #1 starts with {(curly braces) whereas #2 starts with '(apostrophe)
这篇关于MVC:虽然从控制器检索通过JSON对象看来,JavaScript错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!