【问题标题】:How to concatenate the entire results returned from Ajax and print them?如何连接从 Ajax 返回的全部结果并打印出来?
【发布时间】:2021-10-04 04:23:48
【问题描述】:

我正在尝试连接所有 94 个结果并将其返回到 #title1。

下面的所有代码在运行时显示信息方面都可以正常工作,而不是在用户单击按钮时返回每个国家/地区的 94 行。我试图让它在 countryName 标记上循环并添加到结果数组中,一旦循环在国家 94 结束,然后将其推送到 #title1。

有什么帮助吗?

$('#PostalCodeCountryInfoBtn').click(function() {

    $.ajax({
        url: "libs/php/getPostalCodeCountryInfo.php",
        type: 'GET',
        dataType: 'json',
        
        success: function(result) {

            console.log(JSON.stringify(result));

            if (result.status.name == "ok") {

                $('#title1').html(result['data'][0]['countryName'] + " " + result['data'][1]['countryName']);
                $('#title2').html(result['data'][1]['countryName']);
                $('#title3').html(result['data'][2]['countryName']);
                $('#title4').html(result['data'][3]['countryName']);
                $('#title5').html(result['data'][4]['countryName']);
                $('#title6').html(result['data'][94]['countryName']);

            }
        
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // error code
        }
    }); 

});

【问题讨论】:

    标签: javascript jquery json ajax


    【解决方案1】:

    如果你想要全部一行,那就是一张简单的地图并加入。

    var names = result['data'].map(function(country){return country.countryName}).join(" ");
    $('#title1').text(names);
    

    如果你有 94 个不同的元素,你可以循环遍历这些元素(使用一个公共类)

    $(".commonClass").text(function (index) {
      return result['data'][index].countryName;
    });
    

    【讨论】:

      【解决方案2】:

      你可以试试这样 这将遍历 result.data 数组并选择国家名称 per 并将其附加到标题 1

      $('#PostalCodeCountryInfoBtn').click(function() {
      
      $.ajax({
          url: "libs/php/getPostalCodeCountryInfo.php",
          type: 'GET',
          dataType: 'json',
          
          success: function(result) {
      
              console.log(JSON.stringify(result));
               
              if (result.status.name == "ok") {
                  if(result.data.length > 0){
                    for(var i = 0; i < result.data.length; i++){
                      $('#title1').append(result['data'][i]['countryName'])
                    }
                  }
            }
          
          },
          error: function(jqXHR, textStatus, errorThrown) {
              // error code
          }
      }); 
      
      });
      

      【讨论】:

      • 还有你正在使用的所有功能,不需要 jquery。这一切都可以通过内置库轻松实现,并且无需处理额外的 jquery 库文件
      猜你喜欢
      • 2023-01-01
      • 2023-04-08
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 2013-11-28
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多