跨域jquery ajax(Jsonp):未捕获的SyntaxError:意外的令牌:(冒号)
我一直试图从steam api中提取数据,并且没有运气,因为我总是得到上述错误。 这是我正在使用的代码:
var steamurl = "https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?key=[keyomitted]&account_id=38440257&Matches_Requested=10"; function populate_api(){ var json; $.ajax({ 'url': steamurl, 'dataType': "jsonp", 'success': function (data) { alert('success'); json = data; } }); }
我省略了我的API密钥。 我看了很多其他post,无法弄清楚问题出在哪里。 我尝试过使用Jsonp,常规json,我也试过使用"&callback=?"
steamurl
后,但无济于事。
解决方案是添加jQuery代码将调用的本地代理。 您的代理将是服务器端代码(PHP,Python,Ruby等),它将查询转发给Valve,然后将其返回给您的jQuery调用。 但是,您必须使用其支持的格式之一(其中JSONP不是其中之一)。
您将要做的事情的高级视图:
- 创建接受jQuery将传递的参数的PHP文件。 在这种情况下,它看起来像您想要接收的帐户ID和匹配。 不要传递API密钥,这应该存储在PHP文件中
- 在PHP中,使用存储的API密钥和两个传递的值构建您的
steamurl
- 使用此
steamurl
发出对Valve服务器的调用并检索结果。 - 将此响应返回给您的ajax调用
你的PHP看起来像这样(并且应该包括更多的错误检查,因为我只是将$_GET
值作为福音:
$matches = $_GET['matches']; $acct = $_GET['accountid']; $APIKEY = ; $steamurl = "https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?key=$APIKEY&account_id=$acct&Matches_Requested=$matches&format=json"; $json_object= file_get_contents($steamurl); header('Content-Type: application/json'); echo $json_object;
现在您可以使用jQuery来解析此JSON响应。