XMLHttpRequest与django作为服务端的异步交互

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)

效果如图:




仅供新手参考

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值