将json响应转换为javascript数组

时间:2012-12-15 13:27:44

标签: javascript jquery asp.net json

我目前正在收到一个json响应:

[{"id":1,"title":"Test 1 "},{"id":2,"title":"Test 2"}]

我希望将它转换为一个名为'events'的javascript数组,如下所示我可以返回它:例如:

  return {
     events : [
        {
           "id":1,
           "title":"Test 1"
        },
        {
           "id":2,
           "title":"Test 2"
        }
     ]
  };

我从jquery ajax调用得到响应:

    jQuery.ajax({
        type: "POST",
        url: "calendar.aspx/get_all_events",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            document.write(msg.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('Error getting events from database.');
        }
    });

任何人都知道如何将msg或msg.d转换成需要的内容吗?

谢谢,

4 个答案:

答案 0 :(得分:2)

您可以使用:

return {events: JSON.parse(msg.d)};

或者,为了更好的兼容性:

eval("var result = "+msg.d);
return {events: result};

或jQuery解决方案

return {events: $.parseJSON(msg.d)};

答案 1 :(得分:0)

我想你只需要这个:

    success: function (msg) {
        // The event object is what you require
        var eventObj = {events:msg.d};
        document.write(eventObj);
    },

答案 2 :(得分:0)

如果msd.d是

 [{"id":1,"title":"Test 1 "},{"id":2,"title":"Test 2"}] 

然后你可以像这样返回它:

return {
     events : msg.d
  };

但是你必须做一个回调才能返回它。因为ajax是异步的。我添加了回报,因为这就是你想要的。另一种方法是使ajax调用同步。

答案 3 :(得分:0)

function doXHR( callback ) {
   jQuery.ajax( {
        type: "POST",
        url: "calendar.aspx/get_all_events",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function ( event ) {
            callback && callback( event );
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('Error getting events from database.');
        }
    });
}

doXHR( function( event ) {
    var data = { events: event.d };
    // Do other stuff with data here (processing, displaying, etc.).
    // You can call other functions here and feed them with data.
} );

请注意,XHR请求是异步的。您不能简单地返回XHR请求数据。您必须将所有进一步的代码放入回调函数中,以便它可以在数组可用时处理它。