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

后端 未结 1 1526
耶瑟儿~
耶瑟儿~ 2021-01-07 14:16

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 = \"h         


        
相关标签:
1条回答
  • 2021-01-07 15:19

    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.

    0 讨论(0)
提交回复
热议问题