MayoMan MayoMan - 4 months ago 8
JSON Question

Why can I not extract the data from this basic JSON Example

This is my Java script

function displayCustomerData( p_customername )
{
$.ajax({
url: 'myservlet',
type: 'GET',
data: { requesttype : "getcustomerdata" ,
customername : p_customername } ,
contentType: 'application/json; charset=utf-8',
success: function ( data )
{
$("#usernametxt").val( data.customer);
},
error: function () {
alert("Error loading customer data");
}
});


on the server side I generate the JSON using the Gson library

Gson gson = new Gson();

return gson.toJson( customerData );


customerData is a simple POJO with two String fields

I have a breakpoint at the Success response from the server

This is what the "data" variable contains in my debugger when I try to get the data from it

data "{"customer":"cuatomer A","userName":"user A"}"


but on my browser console when I do "data.customer" it tells me that customer is undefined ?
This indicates that there is something wrong with the JSON data but I don't see anything wrong and I can't stare at it any longer... anyone see anything?

I have tried it on Chrome and Firefox incase it was a browser issue, same problem on both.

Answer

you can parse the Data like using JSON.parse(data) and try for data.customer u can get .the result ....

 function displayCustomerData( p_customername ) 
   {       
       $.ajax({
           url: 'myservlet',
           type: 'GET',
           data: { requesttype : "getcustomerdata" , 
                   customername : p_customername } ,
                   contentType: 'application/json; charset=utf-8',
                   success: function ( data ) 
                   {
                        var data1 = JSON.parse(data);
                       $("#usernametxt").val( data1.customer);
                   },
                   error: function () {
                       alert("Error loading customer data");
                   }
       });
Comments