简体   繁体   English

$ .getJSON不起作用,但是访问查询URL会返回数据

[英]$.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: 我无法请求网址抛出以下javascript / jquery代码:

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

When I was browsing the same url, I am getting data. 当我浏览相同的URL时,我正在获取数据。

First, check that you're actually loading the jQuery library in your browser. 首先,检查您是否正在浏览器中实际加载jQuery库。 If entering jQuery() or $() in the console returns undefined or [] , then you're not loading the jQuery library in the page. 如果在控制台中输入jQuery()$()返回undefined[] ,则您不会在页面中加载jQuery库。

Second, the print method in your python code prints the data, but does not return it back to the calling function. 其次,您的python代码中的print方法将打印数据,但不会将其返回给调用函数。

To fix this, change print to return . 要解决此问题,请将print更改为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. 您的print语句不执行任何操作,此代码段的全部目的是获取服务器环境的地址。

In fact, this can all be done in one single line: 实际上,所有这些都可以在一行中完成:

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

通过使用jsonp请求来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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