Problem when returning a list of JSON objects with AJAX, I can not access the properties of the object

3

Good morning, I have this web service:

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string ObtenirProvinciaByPoblacio(int CodiProvincia)
    {
        clsCRUD _ou2 = new clsCRUD();
        try
        {
            _ou2.Connectar();
            List<clsProvincies> LlistaProvincies = clsDALProvincies.getList(_ou2, CodiProvincia);
            _ou2.Desconnectar();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string resultat_Json = jss.Serialize(LlistaProvincies);
            return resultat_Json;
        }
        catch (Exception ex)
        {
            throw;
        }

Which returns a list of objects (In this case there is only one object in the list, but it is not relevant). And in the ajax function I have this:

 $.ajax({
                url: "/WebServiceCV.asmx/ObtenirProvinciaByPoblacio",
                data: "{'CodiProvincia': '" + Codiprovincia + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {                                          

                    $.each(data, function (index, item) {
                        alert(item);
                    });                  
                },
                error: function (request, status, error) {
                    alert(request.responseText);
                },
                failure: function (response) {
                    alert("arriva al failure");
                }
            });

The alert shows me the object: [{"Codi":25,"Nom":"LLEIDA"}] But I can not get the values Codi and Nom to work with them. In theory it would be item.Codi or item.Nom right? I have tried several options but I do not get anything.

    
asked by Xavier 28.01.2016 в 17:08
source

6 answers

0

It works for me, thanks. The code looks like this:

$.ajax({
                url: "/WebServiceCV.asmx/ObtenirProvinciaByPoblacio",
                data: "{'CodiProvincia': '" + Codiprovincia + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {                                          
                    var valors = JSON.parse(data.d);
                    $.each(valors, function (index, item) {
                        console.log(item.Codi);
                        console.log(item.Nom);
                    });
                },
                error: function (request, status, error) {
                    alert(request.responseText);
                },
                failure: function (response) {
                    alert("arriva al failure");
                }
            });
    
answered by 28.01.2016 / 17:38
source
2

If you are only interested in a single item on the list because you do not use:

List<clsProvincies> LlistaProvincies = clsDALProvincies.getList(_ou2, CodiProvincia);
clsProvincies provincia = LlistaProvincies.First();
_ou2.Desconnectar();
JavaScriptSerializer jss = new JavaScriptSerializer();
string resultat_Json = jss.Serialize(provincia);
return resultat_Json;

As you will see when using the First () you only take a single item that will be sent as json to the customer.

On the other hand I see that you use $.each where you are going through each item of the array that the json returns, what I do not understand is how it can be that data generates in each item an array instead of being an simple item.

Did you not evaluate a breakpoint in javascript to be able to inspect the content of data ? you can use the browser tools to do this

    
answered by 28.01.2016 в 17:36
2

You comment that "In the alert the object shows me well: [{"Codi":25,"Nom":"LLEIDA"}]"

$.each(data, function (index, item) {
    alert(item);
});

Check the data variable, you may have been returned [[{"Codi":25,"Nom":"LLEIDA"}]] .

If so, you would have to put item[0].Codi .

    
answered by 28.01.2016 в 18:58
2

Just doing item.Codi should return 25 and item.Nom the name.

Your code would remain like this:

$.each(data, function (index, item) {
                        console.log(item.Codi);
                        console.log(item.Nom);
});  

DEMO

var data = [{"Codi":25,"Nom":"LLEIDA"}];

$.each(data, function (index, item) {
                        console.log(item.Codi);
                        console.log(item.Nom);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 28.01.2016 в 17:16
1

What happens if instead of using

var valors = JSON.parse(data.d);

You return a class like json without serializing it

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<clsProvincies> ObtenirProvinciaByPoblacio(int CodiProvincia)
{

    clsCRUD _ou2 = new clsCRUD();

    _ou2.Connectar();
    List<clsProvincies> LlistaProvincies = clsDALProvincies.getList(_ou2, CodiProvincia);
    _ou2.Desconnectar();

    return LlistaProvincies;
}

As you will see, you return the list directly without serializing json, you will see that the list of provinces is returned directly and not a string

    
answered by 28.01.2016 в 17:47
0

Because of the alert you show ( [{"Codi":25,"Nom":"LLEIDA"}] ), the result returned is an array of objects and not an object itself. So you would not access it with item.Codi e item.Nom but with item[0].Codi e item[0].Nom (there is only one object so the index would be 0)

    
answered by 28.01.2016 в 17:16