0

I am trying to call a web service, which returns valid JSON. An example of the output is the following (a list with two entries):

{"d":"[{\"Id\":9,\"Name\":null,\"User\":null,\"Email\":\"email@gmail.com\",\"Phone\":\"121212121\",\"Address\":null,\"Address2\":null,\"City\":null,\"ZipCode\":\"8700\",\"Country\":null,\"TeachingSkills\":[]},{\"Id\":11,\"Name\":null,\"User\":null,\"Email\":\"email@gmail.com\",\"Phone\":\"1212121\",\"Address\":null,\"Address2\":null,\"City\":null,\"ZipCode\":\"3520\",\"Country\":null,\"TeachingSkills\":[]}]"}

Now I want to iterate the items in this list, and print the names out.

So I have tried the following:

   function loadTutors() {
        var url = '<%= ResolveUrl("~/services/tutorservice.asmx/gettutors") %>';
        $.ajax({
            type: "POST",
            data: "{'data':'" + 'test-data' + "'}",
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (d) {
                loadMap(d);
            },
            error: function () {
            }
        });
    }

    function loadMap(tutors) {
        var locations = [];
        $.each(tutors.d, function (obj) {
            $('#text').append(obj.Email);
        }); 
});

The output of label text is empty. If I say $.each(tutors) is it also empty.

I have tried a lot of editions, and the best I've outputted was a long list of random numbers I have no clue where came from.

What am I doing wrong here?

EDIT:

Attemps from answers.

Parsing to JSON and iterating - this results in many alert boxes with numbers (0..1...2...3..)

function loadTutors() {
        var url = '<%= ResolveUrl("~/services/tutorservice.asmx/gettutors") %>';
        $.ajax({
            type: "POST",
            data: "{'data':'" + 'test-data' + "'}",
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (d) {
                loadMap(JSON.parse(d.d));
            },
            error: function () {
            }
        });
    }

    function loadMap(tutors) {
        var locations = [];
        $.each(tutors, function (obj) {
            alert(obj.toString());
            $('#text').append(obj.Email);
        }); });
4

1 回答 1

1

使用 JSON.parse 将 json 字符串解析为对象

success: function (d) {
   loadMap(JSON.parse(d.d));
},


function loadMap(tutors) {
        var locations = [];
        $.each(tutors, function (i, obj) {
            alert(obj.toString());
            $('#text').append(obj.Email);
        }); });
于 2013-09-11T13:18:32.217 回答