這幾天想提高一下python的水準,本來想弄個24點運算,在網頁上輸出結果的,結果整著整著,就轉移到了Django+jQuery上面來了。
最後,興趣轉移到了django如何使用AJAX架構上。google了一些網頁,好像還很複雜的樣子,偶記得當時玩PHP時好像沒有那麼複雜啊?學著網頁上的例子來了一遍,感覺還是太麻煩。然而,當google AJAX架構的時候,居然發現jQuery是直接支援AJAX的,那麼,還使用其它的plugins支援AJAX肯定是走入了歧路。鼓搗了一陣,終於找到了辦法,留貼為記:
HTML檔案/模板(index.html, 改編自http://hi.baidu.com/cpojutwoiebpvze/item/95e9c9be3b75c67d254b09d2):
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>GoogleJavaScript</title>
<script type="text/javascript" src="/static/jquery.js"></script>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startAA() {
//createXMLHttpRequest();
//xmlHttp.onreadystatechange = handleStateChange;
//var i=12;
//var qurl = "/ajax/getdata/?ts="+new Date().getTime();
//xmlHttp.open("GET", qurl, true);
//xmlHttp.send(null);
$.ajax({
data:
"ts="+new Date().getTime(),
//{
//id: 'ts='+new Date().getTime(), // id,
//value: 'ts='+new Date().getTime(), // id,
//},
url: "/ajax/getdata",
complete: function(XMLHttpRequest, textStatus) {
$('p').text(XMLHttpRequest.responseText);
if(XMLHttpRequest.readyState == 4) {
if(XMLHttpRequest.status == 200) {
document.getElementById("txt").value = XMLHttpRequest.responseText;
document.getElementById("txtID").value=XMLHttpRequest.responseText;
}
}
},
type:'GET',
});
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
document.getElementById("txt").value = xmlHttp.responseText;
document.getElementById("txtID").value=xmlHttp.responseText;
}
}
}
function startCCC() {
$.get("/ajax/getdata",
"ts="+new Date().getTime(),
function(data){
$('p').text(data);
$("#txt").val(data);
$("#txtID").val(data);
// another method, refer to "http://blog.csdn.net/yandt/article/details/5751098"
// $("#txtID")[0].value = data;
}
);
}
</script>
</head>
<body >
<div>
<input id="ok" value="ok" type="submit" onclick="startCCC();" />
<br>
<input id="txtID" type="text" style="width:600px;" value="{{ggg}}" />
<br>
<textarea id="txt" style="width:600px; height:400px;" onkeyup="startAA();"> ... </textarea>
<br>
</div>
<p></p>
</body>
</html>
呵呵,用jQuery簡單清晰多了
mysite的urls.py
(r'^ajax/', include('ajax_jq.urls')),
app的urls.py:
(r'^index/', views.index),
(r'^getdata/', views.getdata),
views.py:
def index(request):
ggg="hhhhhhhhh"
return render_to_response("index.html",locals())
FIB = [0,1]
def get_fib_sequence():
global FIB
FIB.append(FIB[-1] + FIB[-2])
return FIB
def getdata(request):
gg="2000-9-9"
if request.GET:
gg="nihao a "
if request.REQUEST.has_key("ts"):
gg = request.REQUEST["ts"]
global FIB
get_fib_sequence()
ss = " --- Fibonacii number: %d,%d" % (FIB[0], FIB[1])
gg+= ss
return HttpResponse(gg)
開啟Chrome,輸入127.0.0.1:8000/ajax/getdata,工作OK