如何获取 Ajax returns 具有多个值的对象的数组并附加到 HTML

How to get Ajax returns an array with objects with multiple values and append to HTML

我正在尝试使用多个数组获取响应并传递给视图,以便用户可以单击它并向另一个端点发出请求。

响应有值和文本。

  <body>
        <div class="container">
            <div class="text-center">
                <h3>Get Prices</h3>
                <hr>
                <h3>Price 1</h3>
                <p id="price1"></p>

                <hr>
                <h3>Price 2</h3>
                <p id="price1"></p>

                <hr>
                <h3>Price 3</h3>
                <p id="price1"></p>

                <hr>
                <h3>Price 4</h3>
                <p id="price1"></p>
            </div>
        </div>

        <script>
         //http://datarecapture.premiumpension.com:8089/api/Prices/GetAllFundNames


        $(document).ready(function () {
        $.ajax({  
            type: 'GET',
            url: 'http://datarecapture.premiumpension.com:8089/api/Prices/GetAllFundNames',
            contentType: "application/json",

            success: function(results) {
               console.log(results)
               for(var i=0; i< results.length; i++)
                {
                $('#price1').append()
                {
                    value: result[i].FUND_ID[0]
                    Text: result[i].FUND_NAME[0]
                }
                $('#price2').append()
                {
                    value: result[i].FUND_ID[1]
                    Text: result[i].FUND_NAME[2]
                }

                $('#price3').append()
                {
                    value: result[i].FUND_ID[2]
                    Text: result[i].FUND_NAME[2]
                }

                }

        //$('ul#response').html(results);
      },
      error: function(xhr, status, error){

        debugger
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);}
    });

  });

据我了解,您想在每个部分中附加一个条目,其中包含每个基金的 ID 和名称。

如果我是对的,请将您的 for-loop 更改为以下内容:

for(var i=0; i< results.length; i++){
    $('#price'+(i+1)).append('<p class="id">'+results[i].FUND_ID+'</p><p class="name">'+results[i].FUND_NAME+'</p>');
}

如果您已将正确的长度硬编码到条目中,这将执行以下操作: 它开始遍历所有价格 id 标签(以 #price1 开始,而不是 #price0 我添加了 +1)并添加到每两个 p 标签,第一个带有 FUND_ID 和然后用 FUND_NAME。 你可以玩弄它们,让它们以你喜欢的方式出现。

我还建议删除硬编码的 h3p 标签,并将它们也添加到 Ajax 调用中。

我已经用这个修复了


              for (var i = 0; i < resp.result.length; i++) {
                console.log('hello: results', JSON.stringify(resp.result[i].FUND_NAME));


                $('.funds-item-container').append(
                   `<div><h5>Price ${i+1}</h5>
                      <a id='#price${i+1}'>
                       <a href="${resp.result[i].FUND_ID}"> ${resp.result[i].FUND_NAME}</a>
                      </p>
                    </div><hr>`
                );
              }
            },