简体   繁体   English

如何使用 jquery 在 html 中显示我的 json 结果?

[英]How do I display my json result in html using jquery?

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.使用 jQuery ajax 我正在获取一个 json 结果,我试图使用 jQuery 在一个段落元素中显示它,id 为txtResult Here is the .done section of my ajax call这是我的 ajax 调用的 .done 部分

     .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:这是控制台中显示的 json 结果:

    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?谁能让我直截了当?

You have to use JSON.stringify to conver json object to string您必须使用 JSON.stringify 将 json 对象转换为字符串

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

Thanks to the comments above, I found that感谢上面的评论,我发现

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

worked.工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM