Cross domain jquery ajax (Jsonp): Uncaught SyntaxError: Unexpected token : (colon)

梦想的初衷 提交于 2019-12-09 01:54:22

问题


I've been trying to pull data from the steam api, and have had no luck because I always get the above error. Here is the code I am using:

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;
            }
        });
}

I omitted my API key. I have looked at many other posts, and cannot figure out where the problem is. I have tried using Jsonp, regular json, I have also tried using "&callback=?" after steamurl, but to no avail.


回答1:


The solution for this is to add a local proxy that your jQuery code will call. Your proxy will be server side code (PHP, Python, Ruby, etc) that forwards the query on to Valve and then returns it to your jQuery call. You will, however, have to use one of their supported formats (of which JSONP is not one).

A high level view of what you'll be doing:

  • Create PHP file that accepts the parameters jQuery will be passing. In this case, it looks like account ID and matches you want to receive. Do not pass the API key, this should be stored in the PHP file
  • In PHP, build your steamurl using the stored API key, and the two passed values
  • Issue a call to the Valve servers using this steamurl and retrieve the results.
  • Return this response to your ajax call

Your PHP will look something like this (and should include more error checking since I am just taking the $_GET values as gospel:

$matches = $_GET['matches'];
$acct = $_GET['accountid'];
$APIKEY = <YOURKEYHERE>;

$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;

Now you can use jQuery to parse this JSON response.



来源:https://stackoverflow.com/questions/21701750/cross-domain-jquery-ajax-jsonp-uncaught-syntaxerror-unexpected-token-colo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!