0

我有一个 MVC 应用程序,它带有一个名为 Angular 的控制器(我也使用 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 中的控制器

函数 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>

我既没有形象,也没有问题。如果我在控制器中对它们进行硬编码,那就没问题了。

4

4 回答 4

2

警报会显示,我建议使用 console.log(data)

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)); })
 });
于 2013-07-03T13:27:39.610 回答
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。

于 2013-07-03T15:00:52.827 回答
1

The reason it's happening is because JSON is an Object in JavaScript. When you type

alert(data);

It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.

To view the contents of an object you can write a simple function to use with an alert or console.log.

function outputProperties(anObject) {
    var props = '';
    for (var prop in anObject) {
        props += '\n' + prop + ' value: ' + anObject[prop];
    }
    return props;
}

And use it like this

alert(outputProperties(data));
于 2013-07-03T13:36:43.027 回答
1

对于初学者...当您为图像动态构建 src url 时(使用 Angular 的 {{expression}} 语法),您不需要使用“src”属性并使用“ng-src”角度指令。它允许在加载图像之前处理您的 url。

于 2013-07-03T15:01:18.370 回答