我有一个名为Angular的控制器的MVC应用程序(我也使用AngularJS),它有一个名为GetQuestion的动作。该操作返回一个看起来像这样的JsonResult(从Chrome中抓取):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
我的JS功能是这样的:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
但不是我上面写的Json,警告窗口只说[object Object]
好的,那是固定的,很好。但是,正如您可能怀疑的那样,我的目标不是在警报框中显示此数据,而是以某种方式使用它。所以这是我在Angular中的控制器
function QuestionCtrl($ scope){
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
然后是观点:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
@using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
我既没有形象也没有问题。如果我在控制器中对它们进行硬编码,那就没关系了。
答案 0 :(得分:2)
警告会显示,我建议使用console.log(数据)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
或评论指出:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
答案 1 :(得分:2)
我解决了我的第二个问题:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
请注意,它是AngularJS。
答案 2 :(得分:1)
之所以发生这种情况,是因为JSON是JavaScript中的一个对象。当您键入
时alert(data);
它会尝试将对象强制转换为一个字符串,在这种情况下,它只输出它是一个Object的事实。
要查看对象的内容,您可以编写一个简单的函数,用于alert或console.log。
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
并像这样使用
alert(outputProperties(data));
答案 3 :(得分:1)
对于初学者......当你动态构建图像的src url时(使用Angular的{{expression}}语法)你不需要使用“src”属性并使用“ng-src”角度指令。它允许角度时间在加载图像之前处理您的URL。