JS实现的ajax和同源策略(实例讲解)(5)

<script>
方式一=======================================
  //基于JS实现实现用urlencode的方式
  var ele_btn = document.getElementsByClassName("send_ajax")[0];
  ele_btn.onclick = function () { //绑定事件
    alert(5555);
    //发送ajax:有一下几步
    //(1)获取XMLResquest对象
    xmlhttp = new XMLHttpRequest();
    //(2)连接服务器
    //get请求的时候,必用send发数据,直接在请求路径里面发
{#    xmlhttp.open("get","/sendAjax/?a=1&b=2");//open里面的参数,请求方式,请求路径#}
    //post请求的时候,需要用send发送数据
    xmlhttp.open("post","/sendAjax/");
    //设置请求头的Content-Type
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //(3)发送数据
    var ele_num1 = document.getElementsByClassName("num1")[0];
    var ele_num2 = document.getElementsByClassName("num2")[0];
    var ele_ret = document.getElementsByClassName("ret")[0];
    var ele_scrf = document.getElementsByName("csrfmiddlewaretoken")[0];


    var s1 = "num1="+ele_num1.value;
    var s2 = "num2="+ele_num2.value;
    var s3 = "&csrfmiddlewaretoken="+ele_scrf.value;
    xmlhttp.send(s1+"&"+s2+s3); //请求数据
    //(4)回调函数,success
    xmlhttp.onreadystatechange = function () {
      if (this.readyState==4&&this.status==200){
        alert(this.responseText);
        ele_ret.value = this.responseText
      }
    }
  }


方式二====================================================

{#  ===================json=============#}
  var ele_btn=document.getElementsByClassName("send_ajax")[0];
  ele_btn.onclick=function () {

    // 发送ajax

     // (1) 获取 XMLHttpRequest对象
     xmlHttp = new XMLHttpRequest();

     // (2) 连接服务器
    // get
    //xmlHttp.open("get","/sendAjax/?a=1&b=2");

    // post
    xmlHttp.open("post","/sendAjax/");

    // 设置请求头的Content-Type
    var ele_csrf=document.getElementsByName("csrfmiddlewaretoken")[0];
    xmlHttp.setRequestHeader("Content-Type","application/json");
    xmlHttp.setRequestHeader("X-CSRFToken",ele_csrf.value); //利用js的方式避免forbidden的解决办法

    // (3) 发送数据
     var ele_num1 = document.getElementsByClassName("num1")[0];
    var ele_num2 = document.getElementsByClassName("num2")[0];
    var ele_ret = document.getElementsByClassName("ret")[0];


    var s1 = ele_num1.value;
    var s2 = ele_num2.value;
    xmlHttp.send(JSON.stringify(
      {"num1":s1,"num2":s2}
    )) ;  // 请求体数据
    // (4) 回调函数 success
    xmlHttp.onreadystatechange = function() {
      if(this.readyState==4 && this.status==200){
        console.log(this.responseText);
        ele_ret.value = this.responseText
      }
    };
  }







</script>

views.py

def sendAjax(request):
  num1=request.POST.get("num1")
  num2 = request.POST.get("num2")
  ret = float(num1)+float(num2)
  return HttpResponse(ret)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1125.html