循环通过json返回undefined

时间:2012-12-11 19:13:08

标签: javascript asp.net vb.net json web-services

我有一个返回JSON对象的web服务,但是当我尝试遍历它时,每个对象中的每个项都返回undefined

这是从webservice

返回的JSON对象
[{"result":14,"question":"6 - 7  مرات اسبوعيا","aID":70},{"result":29,"question":"3 - 5 مرات اسبوعيا","aID":71},{"result":41,"question":"مرة واحدة اسبوعيا","aID":72},{"result":14,"question":"1 - 3 مرات شهريا","aID":73}]

以及我如何循环它:

var resultAsJson = data.d;
$.each(resultAsJson, function (index, resObject) {
    $('#pollResults').append('<p><strong>' + resObject.result + ' ' +
                resObject.question + '</strong></p>');
    alert(resObject.question);

});

------------------ UPDATE ------------------

嗨,大家好 上面的代码运行正常,问题是我从webservice返回的JSON响应被序列化如下:

                Dim m_result As New Data.Objects.ObjectParameter("Result", GetType(Boolean))
            Dim lstofresult As List(Of addPollvote_Result) = Context.addPollvote(para_pid, para_aid, Date.Now, m_UID, Nothing, HttpContext.Current.Request.ServerVariables("REMOTE_ADDR"), Nothing, m_result).ToList
            Dim m_json As New Script.Serialization.JavaScriptSerializer
            Return m_json.Serialize(lstofresult)

当我删除序列化并刚刚返回列表时,它工作得很完美,请参阅下面的工作代码。

                Dim m_result As New Data.Objects.ObjectParameter("Result", GetType(Boolean))
            Dim lstofresult As List(Of addPollvote_Result) = Context.addPollvote(para_pid, para_aid, Date.Now, m_UID, Nothing, HttpContext.Current.Request.ServerVariables("REMOTE_ADDR"), Nothing, m_result).ToList
            Return lstofresult

它完美无缺。

3 个答案:

答案 0 :(得分:2)

确保resultAsJson实际上是一个JSON对象而不是一个字符串,它应该可以工作(see this jsfiddle) - 使用resultAsJson = JSON.parse(resultAsJson)进行从字符串到json对象的转换。

答案 1 :(得分:0)

问题似乎是您的数据源。

我会使用'for'循环进行测试:

var resultAsJson = data.d;
var resultAsJsonLength = resultAsJson.length;

for(i=0;i<resultAsJsonLength;i++) {
    $('#pollResults').append('<p><strong>' + resultAsJson[i].result + ' ' +
    resultAsJson[i].question + '</strong></p>');

    alert(resultAsJson[i].question);
 }

您将不得不提供有关您如何访问数据的更多信息,这似乎是您问题的基础......

答案 2 :(得分:0)

放手一搏。我假设您正在使用jQuery:

// The JSON String from the web service
var jsonString = '[{"result":14,"question":"6 - 7  مرات اسبوعيا","aID":70},{"result":29,"question":"3 - 5 مرات اسبوعيا","aID":71},{"result":41,"question":"مرة واحدة اسبوعيا","aID":72},{"result":14,"question":"1 - 3 مرات شهريا","aID":73}]';

// Parse the JSON string into a JS object
var jsonObj = JSON.parse(jsonString);

// Loop through, and pull what you need from it
$(jsonObj).each(function() {
    console.log(this.result + " " + this.question); 
});