简体   繁体   中英

$.getJSON doesn't work, but accessing the query URL returns data

#!/usr/bin/python
import json
import cgi
import os

print 'Content-Type: application/json'
print 
response={'host':cgi.escape(os.environ["REMOTE_ADDR"])}
jsondata=json.dumps(response)
print jsondata

I am unable request url throw the following javascript/jquery code:

jquery.getJSON("http://ourdomain/cgi-bin/serverscript.py", function(data){
    alert("----------");
 });

When I was browsing the same url, I am getting data.

First, check that you're actually loading the jQuery library in your browser. If entering jQuery() or $() in the console returns undefined or [] , then you're not loading the jQuery library in the page.

Second, the print method in your python code prints the data, but does not return it back to the calling function.

To fix this, change print to return . Also, I'd suggest changing your function to the following:

response = {'host' : cgi.escape(os.environ["REMOTE_ADDR"])}
return json.dumps(response)

Your print statements don't do anything and the entire purpose of this code snippet is to get the address of the server environment.

In fact, this can all be done in one single line:

return json.dumps( { 'host' : cgi.escape( os.environ[ "REMOTE_ADDR" ] ) } )

通过使用jsonp请求来解决。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM