【问题标题】:How do I display my json result in html using jquery?如何使用 jquery 在 html 中显示我的 json 结果?
【发布时间】:2021-12-03 01:32:18
【问题描述】:

使用 jQuery ajax 我正在获得一个 json 结果,我试图使用 jQuery 在 ID 为 txtResult 的段落元素中显示该结果。这是我的 ajax 调用的 .done 部分

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

        console.log(result);

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

这是控制台中显示的 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

 ​我显然做错了,虽然结果显示在控制台中,但页面上没有任何内容。谁能直截了当?

【问题讨论】:

  • 看来result['data'] 是一个有很多属性的对象。您需要指定要显示的属性。 $('#txtResult').val(result.data.countryName) 例如。另请注意,我使用的是.val() 函数,而不是.html()
  • 给定前缀txt,它很可能是一个文本框<input type='text',所以您需要.val(..) - 包括您的txtResult 的html 以进行确认。

标签: jquery json


【解决方案1】:

您必须使用 JSON.stringify 将 json 对象转换为字符串

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

输出

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

【讨论】:

    【解决方案2】:

    多亏了上面的cmets,我才发现

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

    工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 2023-03-11
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多