通过AJAX(ASP.NET MVC)将json结果附加到div

时间:2017-04-04 08:24:02

标签: javascript jquery asp.net json ajax

我有AJAX调用,并且返回给我JSON

这是AJAX调用

<script>
$('#display').click(function () {
    var vacancyId = $("#vacancy").val();
    var model = {
        vacancyId: vacancyId
};

    $.ajax({
        url: '@Url.Action("QuestionBlocks", "Questions")',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        type: 'POST',
        dataType: 'json',
        processData: false,
        success: function (data) {
            $(".list").append('<div>' + data.Question1 + '</div>');

        }
    });
        });

这是服务器端

  [HttpPost]
    public ActionResult QuestionBlocks(int vacancyId)
    {
        var items = db.QuestionBlocks
                      .Where(x => x.Interview.VacancyId == vacancyId)
                      .Select(x => new 
                      {
                          ID = x.Block_ID.ToString(),
                          Question1 = x.Question1,
                          Question2 = x.Question2,
                          Question3 = x.Question3,
                          Question4 = x.Question4,
                          Question5 = x.Question5,
                          Question6 = x.Question6,
                          Question7 = x.Question7,
                          Question8 = x.Question8,
                          Question9 = x.Question9,
                          Question10 = x.Question10,

                      })
                      .ToList();
        return Json(items, JsonRequestBehavior.AllowGet);
    }

它会返回这样的数据

  

{ID:“1087”,问题1:“Расскажитеосебе”,问题2:“告诉我   你”,...}

我的问题 - $(".list").append('<div>' + data.Question1 + '</div>');效果很好,但显示undefined

为什么会这样?

3 个答案:

答案 0 :(得分:0)

听起来你需要将数据解析为JSON。尝试使用它:

@Entity

答案 1 :(得分:0)

好像data里面有一个数组,所以请尝试这样的成功代码:

$.ajax({
    url: '@Url.Action("QuestionBlocks", "Questions")',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(model),
    type: 'POST',
    dataType: 'json',
    processData: false,
    success: function (data) {
        var question1 = data[0];
        $(".list").append('<div>' + question1.Question1 + '</div>');

    }
});

答案 2 :(得分:0)

我认为它不会返回$q = clone $query; $q->select('count(distinct t.hotel) as count'); $r = $q->getQuery()->getArrayResult(); echo $r[0]['count']; exit(); 。你确定吗? {ID: "1087", Question1: "Расскажите о себе", Question2: "Tell about you",…}将是数组(ToList())。

items

首先得到:

[{ID: "1087", Question1: "Расскажите о себе", Question2: "Tell about you",…}]