如何使用jQuery从JSON对象的数组中获取值?

时间:2018-12-04 20:05:44

标签: jquery html json

这是JSON对象:

{
  'id' => 'itemGuitar',
  'description' => 'Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.',
  'price' => 5695.99,
  'urls' => array('http://www.thewho.com/',
                  'http://en.wikipedia.org/wiki/Pete_Townshend')
}

这是我的getJSON代码:

$.getJSON("getDetailsJSON.php?ImageID=" + escape(itemName), function (json) {
         var info = "<p>id: " + json["id"] + "</p>" +
             "<p>description: " + json["description"] + "</p>" +
             "<p>price: $" + json["price"] + "</p>" +
             "<p>urls:</p><ul>";
        $.each(json["urls"], function (i) {
             info += "<li><a href='" + this[i] + "'>" + this[i] + "</a></li>";
        });
        info += "</ul>";
        $("#description").append(info);
 });

专门查看:

$.each(json["urls"], function (i) {
     info += "<li><a href='" + this[i] + "'>" + this[i] + "</a></li>";
});

我的问题是“ urls”循环中的值不正确。我一次用列表形式的一个字母来获取https,而不是每个列表元素都包含完整地址。

1 个答案:

答案 0 :(得分:0)

jQuery documentation for each

  

对于数组,每次回调都会传递一个数组索引和一个对应的数组值。 (也可以通过$SomeString = '[square]' $SafeString = [regex]::Escape( $SomeString ) Get-ChildItem -Recurse | Where-Object { $_.Name -match $SafeString } | ForEach-Object { $_ | Rename-Item -NewName $($_.Name -replace $SafeString, '') -WhatIf } 关键字访问该值,但是Javascript始终会将PS D:\PShell> D:\PShell\SO\53619911.ps1 What if: Performing the operation "Rename File" on target "Item: D:\PShell\DataFi les\some[square]file.txt Destination: D:\PShell\DataFiles\somefile.txt". What if: Performing the operation "Rename File" on target "Item: D:\PShell\DataFi les\some[square]file2.txt Destination: D:\PShell\DataFiles\somefile2.txt". 的值包装为this,即使它是简单的字符串或数字值。)

因此,在您的代码中this是迭代中当前元素的索引,而Object是当前URL。

i

甚至更好,明确使用值参数

this