这几天想提高一下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