XMLHttpRequest, 比较原始的一种异步交互方式,直接上代码:
前端代码:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.1//EN"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html lang='en'>
<meta charset='utf-8'>
<head>
<title>测试ajax</title>
<script>
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject)
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
else if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
}
//GET的发送方式
function startRequest(){
createXMLHttpRequest();
xmlHttp.open('GET','/home/back?name=littleget',true); //GET发送数据的方式
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)//判断返回码
alert('已经连接'+xmlHttp.responseText)
}
xmlHttp.send(null); //GET发送的内容不再send()中
}
//POST的发送方式
function startPOST(){
createXMLHttpRequest();
xmlHttp.open('POST','/home/back/',true);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
alert('POST已经连接'+xmlHttp.responseText)
}
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //POST发送必须加请求头
xmlHttp.send('name=littlepost');
}
</script>
<input type='button' value='test' onClick='startRequest()'>
<input type='button' value='post' onClick='startPOST()'>
</head>
</body>
JDANGO作为服务端的代码:
def back(request):
>---if request.method == 'POST':
>--->---content = request.POST.get('name')
>--->---return HttpResponse('POST receive success, name is ' + content)
>---else:
>--->---content = request.GET.get('name')
>--->---return HttpResponse('GET receive success, name is ' + content)
效果如图:
仅供新手参考