Ric*_*res 6 c# ajax asp.net-mvc jquery
我正在尝试获取一个带有对C#方法的AJAX调用的列表,并使用jQuery显示其项目,但我无法做到.这是我得到的:
public string test()
{
return "test ok";
}
$.ajax({
type: "POST",
url: "Computer/test",
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
Run Code Online (Sandbox Code Playgroud)
这按预期工作,我得到一个'test ok'字符串的警报.但是,如果我尝试返回一个列表,我无法在jquery中遍历它.
public List<string> testList()
{
List<string> test = new List<string>;
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);
}
});
Run Code Online (Sandbox Code Playgroud)
使用此代码,我收到以下错误:
System.Collections.Generic.List`1 [System.String]
希望你能帮助我,谢谢.
Kha*_* TO 10
使用Json
与服务器端JsonRequestBehavior.AllowGet
,检查出的原因,我们必须使用JsonRequestBehavior
在为什么JsonRequestBehavior需要?:
public JsonResult testList()
{
List<string> test = new List<string>;
test.Add("test1");
test.Add("test2");
return Json(test,JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
你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);
});
Run Code Online (Sandbox Code Playgroud)
success
并且error
已弃用,使用.done
和fail
替代
归档时间: |
|
查看次数: |
17416 次 |
最近记录: |