jQuery$.getJSON抛出意外令牌
jQuery $.getJSON throws Unexpected Token
我是JavaScript初学者。我想使用以下URL从Steam Market检索一些数据:
https://steamcommunity.com/market/priceoverview/?country=PL¤cy=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¤cy=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:意外的令牌:
这个代码出了什么问题?
这是您的问题。我运行
$.ajax( "https://steamcommunity.com/market/priceoverview/?country=PL¤cy=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¤cy=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
我最终解决了这个问题。问题是Steam不允许在浏览器中使用JavaScript代码访问他们的市场数据,因为访问控制允许来源。
我已经将JS代码重写为PHP,并发送了相同的请求,但这次是从我自己的WWW服务器:
function get_price() {
$url = "https://steamcommunity.com/market/priceoverview/?country=PL¤cy=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);
}
工作起来很有魅力。
相关文章:
- React JS:未捕获(在承诺中)语法错误:在位置 0 的 JSON 中意外<令牌
- jQuery$.getJSON抛出意外令牌
- 为什么我在下面的..of循环中得到意外令牌
- 组件中的ReactJS意外令牌
- AngularJS $http GET 请求到本地 JSON 文件返回语法错误:意外令牌]
- 巴别塔,意外令牌 (15:33) ::.
- Sencha 2.0 和 Codeigniter RESTful API 生成未捕获的语法错误:意外令牌:
- 在事件上使用 jquery 时出现意外令牌
- JSON 中位置 4 处的意外令牌<
- 意外令牌 ) 在我的代码中
- Electron 和 Babel 6 异步/等待抛出意外令牌
- “JSON.parse(str)”返回“意外令牌c”,但str是一个字符串
- jQuery after() uncatch SyntaxError: 意外令牌 ILLEGAL
- 使用节点javascript的意外令牌ILLEGAL
- Javascript/JQuery-Chrome意外令牌
- Ajax 帖子未捕获语法错误:意外令牌非法
- angularjs-SyntaxError:请求从服务器返回时出现意外令牌
- jquery:使用ember的意外令牌C
- React本机项目中的意外令牌
- 解析有效的 JSON 得到“语法错误:意外令牌非法”