Home > Enterprise >  How do I display my json result in html using jquery?
How do I display my json result in html using jquery?

Time:10-15

Using jQuery ajax I am obtaining a json result which I am trying to display in a paragraph element with the id txtResult using jQuery. Here is the .done section of my ajax call

     .done(function(result, textStatus, jqXHR) {

        console.log(result);

        if (result.status.name == "ok") {
            $('#txtResult').html(result['data']);
        }
    })

and here is the json result as displayed in the console:

    data:
       countryCode: "IT"
       countryName: "Italy"
       distance: "0"
       languages: "it-IT,de-IT,fr-IT,sc,ca,co,sl"
    [[Prototype]]: Object
    status:
       code: "200"
       description: "success"
       name: "ok"
       returnedIn: "120 ms"
    [[Prototype]]: Object
    [[Prototype]]: Object

 ​I am obviously doing something wrong as, although the result is displayed in the console, nothing appears on the page. Can anyone set me straight?

CodePudding user response:

You have to use JSON.stringify to conver json object to string

var str = JSON.stringify(result.data).replace(/",\"/gi, "<br />").replace(/"/gi, "").replace(/{/gi, "").replace(/}/gi, "") ;
$('#txtResult').html(str);

output

countryCode:IT
countryName:Italy
distance:0
languages:it-IT,de-IT,fr-IT,sc,ca,co,sl

CodePudding user response:

Thanks to the comments above, I found that

    $('#txtResult').html(result.data.countryCode);

worked.

  • Related