如何在 JS 中从外部 url 解码多维 JSON?
How to decode multidimensional JSON from external url in JS?
我正在使用这个 API:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
我想根据其 ID 搜索此 API 的名称。
在 PHP 中看起来像这样:
$id = 730; // input ID
$url = 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json';
$content = file_get_contents($url) ;
$data = json_decode($content, true);
$key = array_search($id, array_column($data['applist']['apps'], 'appid'));
echo $data['applist']['apps'][$key]['name'] // returns Counter-Strike: Global Offensive
是否可以在 JS 中复制此过程? 或者我最好创建第二个 PHP 文件并使用 AJAX 访问它?
当然,你可以看到这个问题的答案:Get JavaScript object from array of objects by value of property
但我认为如果你在浏览器中这样做,你会遇到跨域问题:
Access to XMLHttpRequest at 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json'
has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
此 Steam API 正在阻止浏览器中的 js 访问。
Pierre 说得对,您不能从浏览器执行此操作,因为存在跨域问题。您必须通过代理请求才能获取数据。
您可以使用 PHP 从 Steam 中获取数据,然后在客户端访问它。使用来自 Steam 的数据结构,您可以使用 find method on the array.
获取带有您的 ID 的项目
const data = {
applist: {
apps: [
{ appid: 1},
{ appid: 730, name: 'Needle' }
],
}
};
const id = 730;
const row = data.applist.apps.find(item => item.appid === id);
console.log(row); // { appid: 730, name: 'Needle' }
我正在使用这个 API:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
我想根据其 ID 搜索此 API 的名称。
在 PHP 中看起来像这样:
$id = 730; // input ID
$url = 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json';
$content = file_get_contents($url) ;
$data = json_decode($content, true);
$key = array_search($id, array_column($data['applist']['apps'], 'appid'));
echo $data['applist']['apps'][$key]['name'] // returns Counter-Strike: Global Offensive
是否可以在 JS 中复制此过程? 或者我最好创建第二个 PHP 文件并使用 AJAX 访问它?
当然,你可以看到这个问题的答案:Get JavaScript object from array of objects by value of property
但我认为如果你在浏览器中这样做,你会遇到跨域问题:
Access to XMLHttpRequest at 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json'
has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
此 Steam API 正在阻止浏览器中的 js 访问。
Pierre 说得对,您不能从浏览器执行此操作,因为存在跨域问题。您必须通过代理请求才能获取数据。
您可以使用 PHP 从 Steam 中获取数据,然后在客户端访问它。使用来自 Steam 的数据结构,您可以使用 find method on the array.
获取带有您的 ID 的项目const data = {
applist: {
apps: [
{ appid: 1},
{ appid: 730, name: 'Needle' }
],
}
};
const id = 730;
const row = data.applist.apps.find(item => item.appid === id);
console.log(row); // { appid: 730, name: 'Needle' }