从List <string> </string>循环遍历JSON数组

时间:2014-09-23 19:56:34

标签: c# arrays ajax json

我正在向AJAX JSON方法发送C#List<string>。但是我如何迭代那个JSON数组呢?

[WebMethod]
    public static List<string> GetPreviousSaltsAndHashes(string name)
    {
        List<string> prevSalts = new List<string>();
       ....
       ....              
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();



            if (reader.HasRows)
            {
                while (reader.Read())
                {                      
                    prevSalts.Add(reader.GetString(0));
                }

            }

            conn.Close();            


        return prevSalts;
    }


 $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'NewPassword.aspx/GetPreviousSaltsAndHashes',
            data: "{'name':'" + username + "'}",
            dataType: "json",
            success: function (data) {
                PreviousSalts = data.d;
                alert(PreviousSalts);
            },
            error: function (xhr, status, error) {
                var exception = JSON.parse(xhr.responseText);                  
                alert(exception.Message);
            }
        });

//below part is not working. What is the way to iterate?
 $.each(PreviousSalts, function (index, PreviousSalt) {
                console.log(PreviousSalt);
                pass = $('#txtNewPass1').val();
                var combo = pass + PreviousSalt;
                var hash = new String(CryptoJS.SHA3(combo, { outputLength: 512 }));

                if (hash == newhash) {
                    alert("matched");
                    return false;
                }
            });

2 个答案:

答案 0 :(得分:1)

如果可能,您应该切换到Web API。 ASMX正在逐步淘汰,并且JSON支持不佳。我已经能够强制ASMX像这样返回JSON:

[WebMethod]
public static void GetPreviousSaltsAndHashes(string name)
{
    List<string> prevSalts= //blah blah, retrieve data
    HttpContext.Current.Response.ContentType="application/json";
    HttpContext.Current.Response.Write(JsonConvert.SerializeObject(prevSalts));
}

显然,您失去了内容协商,而您正在使用过时的技术。您应该切换到Web API。实际上,代码与您发布的代码大致相同。你只需要修理路线。

您的JavaScript从未到达任何数据的$.each行。那是因为jQuery AJAX默认是异步的。它会在收到响应后调用成功函数。所以将该代码放在一个函数中,并告诉jQuery的成功处理程序要调用哪个函数。

$.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: 'NewPassword.aspx/GetPreviousSaltsAndHashes',
        data: "{'name':'" + username + "'}",
        dataType: "json",
        success: function (data) {
            PreviousSalts = data.d;               
            alert(PreviousSalts);
            HandleResponse(PreviousSalts);
        },
        error: function (xhr, status, error) {
            var exception = JSON.parse(xhr.responseText);                  
            alert(exception.Message);
        }
    });

 function HandleResponse(PreviousSalts){
 $.each(PreviousSalts, function (index, PreviousSalt) {
            console.log(PreviousSalt);
            pass = $('#txtNewPass1').val();
            var combo = pass + PreviousSalt;
            var hash = new String(CryptoJS.SHA3(combo, { outputLength: 512 }));

            if (hash == newhash) {
                alert("matched");
                return false;
            }
        });
}

答案 1 :(得分:0)

首先,您需要将列表序列化为JSON。 JSON只是数据的JavaScript字符串表示。 .NET提供了简单的功能来实现这一目标。这是一篇很好的信息:

Serializing a list to JSON

其次,除非.each代码段已经正确嵌入到回调函数中,否则您需要从AJAX请求的success方法中调用该代码。