我想(最新的)Web.py和AJAX互相玩好,但到目前爲止,我沒有太多運氣。長話短說,我在本地開發計算機上運行服務器端(Web.py)和客戶端(Javascript),但不知何故,我的所有AJAX GET請求都顯示爲OPTION請求。從我讀過的,這是典型的跨域請求的情況下,但因爲我在本地主機上運行此我不知道發生了什麼。無法獲取Web.py和jQuery來制定一個AJAX GET請求(它轉向一個OPTIONS請求)
這裏的服務器端代碼:
import web
import json
def make_text(string):
return string
urls = ('/', 'mainScreen',
'/update', 'update'
)
app = web.application(urls, globals())
global content
content = {'key1': 'value1', 'key2': 'value2'}
def getPayload():
return content
class mainScreen:
def GET(self):
web.header('Content-Type', 'application/json')
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
return getPayload()
def OPTIONS(self):
web.header('Content-Type', 'application/json')
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
return getPayload()
class update:
def POST(self):
global content
content = web.input(_method='post')
return "DONE."
if __name__ == '__main__':
app.run()
這裏的客戶端代碼:
<html>
<head>
<title>WTF</title>
<script type="text/javascript" src="../static/jquery.js"></script>
<script type="text/javascript">
function dial()
{
console.log("Fire in the hole!");
$.ajax({
url: 'http://0.0.0.0:8080',
contentType: 'application/jsonp',
timeout : 5000,
cache: false,
success: function (data) {
console.log('[ajax] Connection successful! ' + JSON.stringify(data));
},
error:function (jqXHR, textStatus, errorThrown){
console.log(JSON.stringify(jqXHR) + ' ' + textStatus +' '+errorThrown);
}
});
console.log("Done.");
}
$(function() {
dial();
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
這是Firebug的輸出:
消防在洞口! index.html(第9行)完成。
index.html(第24行)[ajax]連接成功! 「」
index.html的(第17行)
注意, 「」 指示該請求得到了空數據。
這是Firebug的網絡面板顯示:
如果我打開Firebug的指示數據的有正常的,但如果是我,很簡單開放http://0.0.0.0:8080/
在任何瀏覽器中,數據顯示爲網頁預期!這裏發生了什麼?
最後,這裏的Web.py的日誌:
[email protected]:~/Desktop/tut$ python app.py
http://0.0.0.0:8080/
127.0.0.1:43796 - - [26/Jul/2013 11:14:59] "HTTP/1.1 OPTIONS /" - 200 OK
我在Ubuntu的方式12.04 LTS編碼。
PS:我也試圖改變響應報頭內Web.py到:
web.header('Content-Type', 'text/plain')
,但沒有奏效。
PS2:將客戶端腳本上的服務器地址更改爲「127.0.0.1:8080」或「localhost:8080」也沒有幫助。