jQuery $ .getJSON抛出了意外的令牌

问题描述 投票:0回答:2

我是一名JavaScript初学者。我想使用以下URL从Steam Market检索一些数据:

https://steamcommunity.com/market/priceoverview/?country=PL&currency=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case#

我在浏览器中收到此回复:

{"success":true,"lowest_price":"0,09\u20ac","volume":"1,017","median_price":"0,10\u20ac"}

但我不能让它在JS中工作。

var amount = prompt("How many cases do you have?\t");
$.getJSON("http://steamcommunity.com/market/priceoverview/?country=PL&currency=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case#",
    function(json) {
    var raw_price = json.lowest_price;
    var price = raw_price.split('&')[0];
    var price_total = price*parseInt(amount);
    alert(price_total + '€');
});

它只是抛弃了我:

未捕获的SyntaxError:意外的令牌:

这段代码出了什么问题?

javascript json steam-web-api
2个回答
0
投票

这是你的问题。我跑了

$.ajax( "https://steamcommunity.com/market/priceoverview/?country=PL&currency=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case" )
  .done(function() {
    alert( "success" );
  })
  .fail(function(jqXHR, textStatus) {
console.log(jqXHR );
});

得到了这个输出

XMLHttpRequest cannot load https://steamcommunity.com/market/priceoverview/?country=PL&currency=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.

这意味着您无法使用JQuery执行此操作。尝试使用Steam的Web API:https://developer.valvesoftware.com/wiki/Steam_Web_API


0
投票

我最终解决了这个问题。问题在于,由于Access-Control-Allow-Origin,Steam不允许使用浏览器中的JavaScript代码访问其市场数据。

我已经将我的JS代码重写为PHP并发送了相同的请求,但这次是从我自己的WWW服务器:

function get_price() {
    $url = "https://steamcommunity.com/market/priceoverview/?country=PL&currency=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case";
    $json = file_get_contents($url);
    $price = json_decode($json);
    $price_case = $price->{"lowest_price"};
    return number_format($price_case, 2);
}

工作就像一个魅力。

© www.soinside.com 2019 - 2024. All rights reserved.