javascript 如何在ajax返回时解析字符串的JSON列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34266884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:28:23  来源:igfitidea点击:

How to parse JSON list of string on ajax return?

javascriptc#jqueryjsonajax

提问by Andrew Kilburn

I have a simple ajax call which returns a serialised list of strings. This is great and I can get the data back. However I'm simply trying to perform an alert on each item in the list. However, I just keep getting back single characters from the list instead. For example if it returned a list with one item in it called "Hello". It would alert "H", "E", "L" etc. Can someone help me change this so it alerts the full string?

我有一个简单的 ajax 调用,它返回一个序列化的字符串列表。这很棒,我可以取回数据。但是,我只是尝试对列表中的每个项目执行警报。但是,我只是不断从列表中取回单个字符。例如,如果它返回一个列表,其中包含一个名为“Hello”的项目。它会提醒“H”、“E”、“L”等。有人可以帮我改变它,以便它提醒完整的字符串吗?

The response received back is very similar to the text above. If the c# variable userList returns a list of strings with just "Andrew" in it. The JQuery will alert "A", "N", "D" etc. If that isn't clear, just let me know.

收到的回复与上面的文本非常相似。如果 c# 变量 userList 返回一个字符串列表,其中仅包含“Andrew”。JQuery 会提醒“A”、“N”、“D”等。如果不清楚,请告诉我。

Thanks

谢谢

C#

C#

[HttpPost]
        public string GetUserList(string Role) {
            List<string> UserList = new List<string>();
            UserList = Roles.GetUsersInRole(Role).ToList();
            return JsonConvert.SerializeObject(UserList);
        }

JQuery

查询

   $('#allRolesDD').change(function () {
        $.ajax({
            method: "POST",
            url: "./GetUserList",
            data: { Role: $(this).val() }
        })
        .done(function (data) {
            $('.roleDD').empty();
            for (i = 0; i < data.length; i++) {
                alert(data[i]);
            }
            console.log("Passed 4");
        })
        .fail(function () {
            console.log("Failed 4");
        })
    });

采纳答案by Atikur Rahman

you can change c# code and jquery like below:

您可以像下面这样更改 c# 代码和 jquery:

C#

C#

[HttpPost]
    public JsonResult GetUserList(string Role) {
        List<string> UserList = new List<string>();
        UserList = Roles.GetUsersInRole(Role).ToList();
        return Json(UserList, JsonRequestBehavior.AllowGet);
    }

JQuery

查询

  $('#allRolesDD').change(function () {
$.ajax({
    method: "POST",
    url: "./GetUserList",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: { Role: $(this).val() }
})
.done(function (data) {
    $('.roleDD').empty();
    for (i = 0; i < data.length; i++) {
        alert(data[i]);
    }
    console.log("Passed 4");
})
.fail(function () {
    console.log("Failed 4");
})
});

回答by Sergii Zhevzhyk

You need to add dataType: "json"into the ajax call because it doesn't know that your response is a json. It assumes that it is a string.

您需要添加dataType: "json"到 ajax 调用中,因为它不知道您的响应是 json。它假定它是一个字符串。

$("#allRolesDD").change(function () {
    $.ajax({
        method: "POST",
        url: "./GetUserList",
        data: { Role: $(this).val() },
        dataType: "json"                   
    })
    .done(function (data) {
        $('.roleDD').empty();

        $.each(data, function (i, v) {
            alert(v);
        });

        // or you could also iterate using for 
        //for (i = 0; i < data.length; i++) {
        //    alert(data[i]);
        //}

        console.log("Passed");
    })
    .fail(function () {
        console.log("Failed");
    })
});

回答by AntiHeadshot

Why don't you return the list as it is instead of a string, the web API will automaticly convert it to json and you can read it as an array in your request?
You just have to add

为什么不按原样返回列表而不是字符串,Web API 会自动将其转换为 json,您可以在请求中将其作为数组读取?
你只需要添加

$('#allRolesDD').change(function () {
    $.ajax({
        method: "POST",
        url: "./GetUserList",
        data: { Role: $(this).val() },
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .done(function (data) {
        $('.roleDD').empty();
        for (i = 0; i < data.length; i++) {
            alert(data[i]);
        }
        console.log("Passed 4");
    })
    .fail(function () {
        console.log("Failed 4");
    })
});

回答by madalinivascu

Try jquery each:

尝试 jquery 每个:

 $.ajax({
            method: "POST",
            url: "./GetUserList",
            data: { Role: $(this).val() },
            success:function (data) {
               $.each(data,function(i,v){
                       console.log(v);
               });
            }
        });