Python CGI对同一jQuery/AJAX请求有不同响应
我正在实现一个系统,让两个网页(HTML + Javascript)通过CGI Python服务器端脚本进行通信。其中一个网页会发出请求:
function doQuery(tweets) {
$.getJSON("http://linuxproj.ecs.soton.ac.uk/~onme1g10/watchitlater/cgi-bin/engine.cgi?loading="+ uid +"&tweets="+ tweets, function(data) {
}
)
.success(function(data) {
//alert("complete: " + data['test']);
if (tweets == 1) {
//console.log('tweets is one')
tweetsData = data;
length = Object.keys(tweetsData["tweets"]).length;
intervalVar = window.setInterval(showTweets, 1000);
intervalVar2 = window.setInterval(queryState, 1500);
//console.log("set intervals");
}
else {
console.log('HERE: ' + data["correct"])
queryData = data;
// Function to update state variables
}
})
.error(function(xhr, textStatus, error) {
//alert("error:" + textStatus);
console.log(xhr);
console.log(textStatus);
console.log(error);
})
.complete(function() {/*alert("complete!");*/ });
}
这个请求中会有 ?tweets=1
或 ?tweets=0
,意思是服务器需要根据这个值返回不同的JSON对象。在服务器端,我有:
if fs.has_key('state'):
createStateFile()
elif fs.has_key('loading'):
# Return JSON objects
print "Content-type: application/json"
print
option = fs['tweets'].value
if option == 0:
response = {'correct':'1'}
print(json.JSONEncoder().encode(response))
else:
response = harvestTweets()
print(json.JSONEncoder().encode(response))
else:
# Return main page
print "Content-type: text/html"
print
main()
但是这个方法不奏效。else部分(当选项为1时)能正常执行,但另一个选项却返回了一个不明确的对象。我尝试了很多方法(比如两种不同的AJAX请求等),但都不行。似乎不支持多个请求或多个返回。有没有什么建议?
1 个回答
0
这个问题其实很简单。在我的Python CGI脚本中,当我写 if tweets == 1: ... else: ...
时,它总是执行else部分,因为我在比较一个来自FieldStorage的字符串“tweets”和数字1。由于它们的类型不同,所以这个比较永远不会为真,因此总是返回相同的结果。