【问题标题】:Return array of strings from MVC to jQuery ASP.NET将字符串数组从 MVC 返回到 jQuery ASP.NET
【发布时间】:2012-03-02 21:36:29
【问题描述】:

我想通过 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 并解析呢?
  • 请发布您的服务器端代码(您的操作方法)。我认为您返回的是包含 system.array[] 的字符串,而不是 JSON 序列化数组。
  • 我不使用 json 如果这不起作用,这是我的计划 B

标签: jquery asp.net-mvc arrays system.array


【解决方案1】:

您可以返回 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);
};

【讨论】:

    【解决方案2】:

    你在后端运行什么?

    基本上,您可能希望先使用 json 或 xml 序列化您的数组。

    如果是 PHP,这里是来自 jQuery .post API 的示例

    例子:post到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,您可以使用库来序列化 json 对象,例如 Googles' gson

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 1970-01-01
      • 2012-08-09
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      相关资源
      最近更新 更多