0
我正在實現一個系統,通過CGI Python服務器端腳本與網頁(HTML + Javascript)進行通信。一個本頁面發出請求:Python CGI以不同的方式迴應相同的jQuery/AJAX請求
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
或,這種想法是服務器必須返回取決於值不同的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子句(其中option == 1)執行正常,但另一個選項返回未指定的對象。我嘗試了很多方法(兩個不同的AJAX請求等),但它不起作用。它不喜歡多個請求或多個返回。有任何想法嗎?
那麼'harvestTweets()'返回什麼? – 2013-03-13 19:49:55
返回: tweets = json.load(myFile) 其中myFile是jason對象文件。 – 2013-03-13 19:51:43
因此,1.爲什麼你不只是讀取並返回該文件而不是解碼然後重新編碼JSON,2.爲什麼你使用'json.JSONEncoder()。encode'而不是'json.dumps' ? – 2013-03-13 19:54:43