无法使用来自ajax调用的返回列表。

21 浏览
0 Comments

无法使用来自ajax调用的返回列表。

我试图通过AJAX调用C#方法来获取列表,并使用jQuery显示其项,但我无法做到。这是我得到的:

public string test()
{
    return "test ok";            
}
$.ajax({
    type: "POST",
    url: "Computer/test",
    success: function (data) {
        alert(data);
    },
    error: function () {
        alert("error");
    }
});

这按预期工作,我得到一个带有“test ok”字符串的警报。但是,如果我尝试返回一个列表,我无法在jQuery中遍历它。

public List testList()
{
    List test = new List;
    test.Add("test1");
    test.Add("test2");
    return test;
}
$.ajax({
    type: "POST",
    url: "Computer/testList",
    dataType: "json",
    success: function (data) {
        var list = data.d;
        $.each(list, function (index, item) {
            alert(item);
        });
    },
    error: function (xhr) {
        alert(xhr.responseText);               
    }
});

使用这段代码,我得到以下错误:

System.Collections.Generic.List`1[System.String]

希望你能帮我,谢谢。

admin 更改状态以发布 2023年5月24日
0
0 Comments

将您的控制器操作更改为返回Json:

public JsonResult testList()
{
    List test = new List;
    test.Add("test1");
    test.Add("test2");
    return Json(test);
}

0
0 Comments

在服务器端使用JsonJsonRequestBehavior.AllowGet,查看我们为什么需要使用JsonRequestBehavior请参考为什么需要JsonRequestBehavior?

public JsonResult testList()
{
    List test = new List;
    test.Add("test1");
    test.Add("test2");
    return Json(test,JsonRequestBehavior.AllowGet);
}

你的JS:

$.ajax({
    type: "POST",
    url: "Computer/testList",
    dataType: "json"
})
.done(function(data){
   var list = data;
   $.each(list, function (index, item) {
       alert(item);
   });
})
.fail(function(xhr){
    alert(xhr.responseText); 
});

successerror已经被弃用,请使用.donefail

0