[英]Return array of strings from MVC to jQuery ASP.NET
我想通过jQuery AJAX调用从MVC函数返回字符串数组。
我的客户端代码是:
function get_categories() {
var url = "/Profile/GetCharacters";
$.post(url, function (data) {
alert(data);
});
但是我看不懂数组元素。 在alert(data)
它总是说system.array[]
;在alert(data[0])
,它总是说s
(即system.array []中的第一个字符),而不是数组元素。
这是我的服务器端代码的简化版本..导致原始文件过于复杂:)
public Array GetCharacters()
{
var ret = new string[10];
ret[0]="abc";
ret[1] = "def";
ret[2] = "ghi";
return (ret);
}
但这给了“ System.string []”,并且在访问单个值时也出现了同样的问题
您可以返回JSON。
例如,您可以向以下控制器操作发出Ajax请求:
public JsonResult GetMyData()
{
SomeClass s = new SomeClass();
s.Property1 = "value";
s.Property2 = "another value";
return Json(s, JsonRequestBehavior.AllowGet); //you will need the AllowGet option to return data to a GET request
}
然后,您的JavaScript可以向控制器发出Ajax请求(使用jQuery的Ajax函数):
var onSuccess = function (data) {
//data will be your s object, in JSON format
};
$.ajax({
type: 'GET',
url: '/ControllerName/GetMyData/',
success: function (data) { onSuccess(data); }
});
编辑:返回数组或列表时,您将需要在Ajax调用中添加Traditional:true选项,如下所示:
var onSuccess = function (data) {
//data will be your s object, in JSON format
};
$.ajax({
type: 'GET',
url: '/ControllerName/GetMyData/',
success: function (data) { onSuccess(data); },
traditional: true
});
我不确定100%为什么这样做(我敢肯定有人会填补我们的空缺),但这使我适应了过去。
再编辑一次 :您可能需要解析JSON,这应该为您创建一个实际的javascript Array对象:
var onSuccess = function (data) {
//data will be your s object, in JSON format
var arr = JSON.parse(data);
};
您在后端运行什么?
基本上,您可能想先使用json或xml序列化数组。
如果是PHP,这是jQuery .post API的示例
示例:张贴到test.php页面并获取以json格式返回的内容。
PHP代码
<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>
jQuery代码
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
如果是JAVA,则可以使用库来序列化Google对象的json对象等json对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.