user2495586
user2495586

Reputation: 253

Trouble retrieving JSON from python script via $.getJSON in javascript

Right now, I'm trying to access data from the education.com API. However, I'm still unable to do so.

Basically, from what I understand, I'm supposed to use this python script to suppress the cross domain restriction for browsers. The python script is called getData.py, and I'm using the following code. Verbatim:

#!/usr/bin/python 

# Import modules for CGI handling 
import cgi, cgitb 
import urllib2 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

#download data from request parameter 'url' 
print "Content-type:text/xml\r\n\r\n" 
url = form.getvalue("url") 
callback = form.getvalue("callback")
req = urllib2.Request(url) 
response = urllib2.urlopen(req) 
data = response.read() 
print callback + "(" + data+ ")"

Then, I need to call the python script in my JavaScript/jQuery code through the $.getJSON. My professor said I need to pass the url of education API, and the call back to this script. I'm unsure as to how I would do this. How would I do this? What is my callback? This is my jquery code. I removed my key from the url for privacy. It is replaced by the word mykey.

$.getJSON("getData.py", { url: "http://api.education.com/service/service.php?
f=schoolSearch&key=mykey&sn=sf&v=4&city=Atlanta&state=ga&Re
sf=json"}, function(data) {  
console.log(data);
});
});

Upvotes: 0

Views: 1994

Answers (1)

falsetru
falsetru

Reputation: 369094

Serialize the retrieved data as json.

#!/usr/bin/python 

# Import modules for CGI handling 
import cgi, cgitb 
import urllib2 
import json

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

#download data from request parameter 'url' 
print "Content-type:text/javascript\r\n\r\n" 
url = form.getvalue("url") 
callback = form.getvalue("callback")
req = urllib2.Request(url) 
response = urllib2.urlopen(req) 
try:
    data = response.read() 
    print callback + "(" + json.dumps(data)+ ")"
finally:
    response.close()

Include callback=? in url. (http://api.jquery.com/jQuery.getJSON/)

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
        <script type="text/javascript">
            var jsonp_url = "cgi-bin/getData.py";
            var url = "http://api.education.com/service/service.php?f=schoolSearch&key=mykey&sn=sf&v=4&city=Atlanta&state=ga&Resf=json";
            $.getJSON(jsonp_url + '?callback=?', {
                url: url
            }, function(data) {
                console.log(data);
                $('body').text(data);
            });
        </script>
    </head>

    <body>
    </body>
<html>

Upvotes: 0

Related Questions