ajax Post數據,並得到返回結果,密碼加密(Select,checkbox)


使用ajax Post數據到后台Server,並從后台返回數據給前端WEB:

urls.py:

from django.conf.urls import url
from aptest import views as aptest
urlpatterns = [
    url(r'^$', aptest.index, name='index'),

]

編輯views.py,定義主頁:

from django.views.decorators.csrf import csrf_exempt #導入csrf_exempt模塊,在前端POST數據時不檢測csrftoken 

#@csrf_exempt #由於csrf機制,在此需要調用該裝飾函數(使POST不檢測token),否則在ajax post數據的時候會提示403 forbiddon。如果通過form序列化(serialize)的方式post數據,會自動生成csrftoken,無需調用該裝飾函數
@login_req() //要寫在csrf_exempt下面,否則不使用form序列化的方式ajax post數據時會提示403 forbiddon
def index(request): #主頁 print request.method a=request.POST.get('a') b=request.POST.get('b') print a,b if a is not None and b is not None: ret=int(a)+ int(b) return HttpResponse(str(ret)) #執行到此處,后面的代碼不會再繼續執行 context={} return render(request,'aptest/index.html',context)

編輯模板index.html:

在其form中定義action值,指向當前頁面,則在ajax post data時無需再定義url,默認將把數據提交到當前頁面。

{% extends "base.html" %}
{% block title %}aptest index{% endblock %}
{% block content %}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script> <!--應用的js腳本文件-->

  <script > <!--加入這段代碼,ajax在POST的時候即可默認提交csrf_token。這段代碼必須要放在html文件中,不能放到調用的.js文件中-->
    $.ajaxSetup({
    data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
    });
  </script>

<p>請輸入兩個數字</p>
<form action="{% url 'aptest:index' %}" > <! -- 此處action表示該form提交到的頁面,此處含義為 aptest應用的index頁面。如果action為空,則需要在ajax post的url中進行定義。action默認留空即表示提交給當前頁面,ajax post url也不需要再定義。 method="POST"不需要定義,在ajax里面定義即可 -->
  {% csrf_token %}
    a: <input type="text" id="a" name="a" > <br>
    b: <input type="text" id="b" name="b"> <br>
   
    <p>result: <span id='result'></span></p>
    <input type="button" id='sum' name='sum' value="cacl">
</form>
<div id="box"></div>

{% endblock %}

base.html:

{% include 'header.html' %}
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% include 'userauth.html' %}
    <h1>My Test site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site2.</p>
    {% endblock %}
    <!-- {% include 'footer.html' %} -->
</body>
</html>

header.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>

編輯index.js,定義js函數:

$(document).ready(function(){

  $('p').css('color','red')
  $('form input[type=button]').click(function(){  //綁定form中tpye=button的input標簽
    a=$('form input[name=a]').val();
    b=$('form input[name=b]').val();
    // alert(a);
    //alert(b);
    $.ajax({
      type: 'POST',
      //url: '/aptest/', 由於在index.html的form的action已經定義了該url,所以此處不需要再定義。 這段js代碼如果直接寫在index.html中,則該url也如此,不變。需要注意最后面必須要有/
      data: {
        a:a,
        b:b
      },
      success:function(response,stutas,xhr){
        $('#result').html(response); //將index view的返回值綁定到id=result的內容中。response參數表示所有從后端返回的值
        alert(stutas); //執行成功返回狀態success
      },
      error:function(xhr,errorText,errorStatus){
        alert(xhr.status+':'+xhr.statusText); //數據提交失敗返回403 forbidden
      }
    });
  });

執行結果:提交a=22,b=3,result返回25

 

index.js提交數據等待,超時:

$(document).ready(function(){

  $('p').css('color','red')
  $('.loading').css('display','none') //隱藏名為.loading的類
  $('#formnum input[type=button]').click(function(){ //選擇id=formnum的form中的元素
    $.ajax({
      type: 'POST',
      //url: '/aptest/',
      // data: {
      //   a:a,
      //   b:b
      // },
      data:$('#formnum').serialize(), //將id=formnum的form中提交的數據以序列化的方式進行提交,無需再具體寫出form中每個input中的內容
      success:function(response,stutas,xhr){
        $('#result').html(response);
        //alert(stutas);
      },
      error:function(xhr,errorText,errorStatus){
        alert(xhr.status+':'+xhr.statusText);
      },
   timeout:500 //設置超時時間,單位毫秒,超過500ms沒有返回結果則報錯 }); }); $(document).ajaxStart(
function(){ //ajax提交數據時顯示等待信息 $('.loading').show(); //.loading是在index.html中定義的class }).ajaxStop(function(){ $('.loading').hide(); }); });

index view打印request.POST內容如下,可以正常接收數據:

<QueryDict: {u'a': [u'33'], u'csrfmiddlewaretoken': [u'5foMcNoH0cALQ0xoK5NKsyYhSLlCdi88'], u'b': [u'2']}>

index.html編輯如下:

{% extends "base.html" %}
{% block title %}aptest index{% endblock %}

{% block content %}

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script>

<p>請輸入兩個數字</p>
<form id="formnum" action="{% url 'aptest:index' %}" >
  {% csrf_token %}
    a: <input type="text" id="a" name="a" > <br><br>
    b: <input type="text" id="b" name="b"> <br>
   
    <p>result: <span id='result'></span></p>
    <input type="button" id='sum' name='sum' value="cacl">
</form><br>
<span class="loading">正在加載中...</span>
<div id="box"></div>

{% endblock %}

執行顯示如下:

 

ajax返回多個值(json格式):

index.js編輯如下:

$(document).ready(function(){

  $('p').css('color','red')
  $('.loading').css('display','none') //隱藏名為.loading的類
  $('#formnum input[type=button]').click(function(){
    $.ajax({
      type: 'POST',
      //url: '/aptest/',
      data:$('#formnum').serialize(),
      dataType:'json', //定義需要返回json格式,如無特殊需要不要定義dataType,否則當放回的數據不是json格式,則無法正常返回數據
      success:function(response,stutas,xhr){
          alert(response); //返回Object Object ,從index view response的數據為:rets=[{'r1':PLUS,'r2':MuLT}]。如果返回的數據類型與前面dataType指定的格式不同,則會執行error函數
        $('#result').html(response[0].r1); //r1,r2是從view的rets中取來的key值
        $('#result2').html(response[0].r2); 
        //alert(stutas);
      },
      error:function(xhr,errorText,errorStatus){
        alert(xhr.status+' error: '+xhr.statusText);
      },
      timeout:500
    });
  });

  $(document).ajaxStart(function(){
      $('.loading').show();
  }).ajaxStop(function(){
      $('.loading').hide();
  });

  // $('input').click(function(){ //點擊按鈕后再加載test.js文件,而不是全局調用
  //     $.getScript('test.js');
  // });



});

index view:

@csrf_exempt
def index(request): #主頁
    print request.method
    import json
    a=request.POST.get('a')
    b=request.POST.get('b')
    if a is not None and b is not None:
        PLUS=int(a) + int(b)
        MuLT=int(a) * int(b)
        rets=[{'r1':PLUS,'r2':MuLT}] #jQuery只能接受這種類型json數據,不加中括號也可以,直接將dict轉換為json格式,js中也就不再需要加index去取值
        retsj=json.dumps(rets) #將pathon對象轉換為json字符串(str),jQuery只能接受這種類型json數據
        return HttpResponse(retsj)
    context={}
    return render(request,'aptest/index.html',context)

index.html:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script>

<p>請輸入兩個數字</p>
<form id="formnum" action="{% url 'aptest:index' %}" >
  {% csrf_token %}
    a: <input type="text" id="a" name="a" > <br><br>
    b: <input type="text" id="b" name="b"> <br>
   
    <p>plus: <span id='result'></span></p>
    <p>multi: <span id='result2'></span></p>
    <input type="button" id='sum' name='sum' value="cacl">
</form><br>
<span class="loading">正在加載中...</span>

執行返回結果:

 

單選按鈕,多選框,下拉列表:

下拉列表參考:http://blog.csdn.net/tiemufeng1122/article/details/44154571

index.html:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/index.js"></script>

<p>請輸入兩個數字</p>
<form id="formnum" action="{% url 'aptest:index' %}" >
  {% csrf_token %}
    a: <input type="text" id="a" name="a" > <br><br>
    b: <input type="text" id="b" name="b"> <br><br>

    <!--定義單選按鈕-->
    sex: <input type="radio" checked="checked" name="sex" value="man" /><input type="radio" name="sex" value="woman" /><br><br><br>

    <!--定義復選框-->
    <label><input type="checkbox" name="fruit" value="apple" />apple </label> 
    <label><input type="checkbox" name="fruit" value="pear" />pear </label> 
    <label><input type="checkbox" name="fruit" value="watermelon" />watermelon </label> <br><br>

    <!--定義下拉列表-->
    Select one:<select id="car" name="car"> <!--index view通過該name名稱得到選擇結果-->
    <option value="Volvo">Volvo</option>
    <option value="Saab" selected="selected">Saab</option> <!--默認選中-->
    <option value="Mercedes" disabled="disabled">Mercedes</option> <!--不可選,灰色-->
    <option value="Audi" title="Audi, your best choice!">Audi</option> <!--鼠標放在上面出現提示信息-->
    </select><br>

    <p>plus: <span id='result'></span></p>
    <p>multi: <span id='result2'></span></p>

    <input type="button" id='sum' name='sum' value="cacl">
</form><br>
<span class="loading">正在加載中...</span>

jquery獲得下拉列表的項的屬性值: alert(("#car option:selected").text())

jquery獲得下拉列表的項的value值: alert(("#car").val())

python后台獲得下拉列表的值:

request.GET['car']

如果通過表單序列化方式提交包含有下拉列表的form,提交的時候使用的是select的name,而不是id。如果使用id,后台接收不到該select的值。

index.js:

$(document).ready(function(){
     // $('#car').css('color','green') //下拉列表設置為綠色//alert($('input:radio:checked').val()); //獲取單選按鈕的值

      //var arr=[];
      //$('input:checkbox:checked').each(function(){arr.push(this.value);}); #獲取復選框的值
      //alert(arr[0]);

      //alert($('#car').val()); //獲取下拉列表的值

});

index.view:

#django中需要使用getlist獲取復選框的值,使用get只能獲取到最后一個值
request.POST.getlist('fruit')

頁面顯示:

使用jQuery的md5插件對密碼進行加密處理。后台通過request.POST.get('name'),request.POST.get('pwd')進行接收。

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/static/jQuery/jQuery.md5.js"></script>
<script>
  $(document).ready(function(){
    $('#login').click(function(){
      var name = $('#uname').val();
      var pass = $('#formlogin input[type=password]').val();
      var passmd5 = $.md5(pass);
      //alert(passmd5+name);

      $.ajax({ 
        type: 'POST',
        url: '/aptest/login/',
        data:{
          name:name,
          pwd:passmd5
        },
        timeout:500
      });

    });
  })

</script>

 

檢查字符串name的長度:alert(name.length)

 查看數據類型:alert($.type(name))

 判斷字符串name是否包含數字:

var pattern = /\d/ig;         //var pattern = /[a-z]+/ig; 檢查是否包含有字母
      if(pattern.test(name))
        {alert(number)}
      else{alert('nonono')};

 return; 將終止函數執行,return后面的語句均不會再被執行。

 

ajax POST數組(array)到后台:

var datas_del = []
datas_del.push(pk_del);


      $.ajax({
        type: 'POST',
        traditional :true,   //需要加上該句,否則在post到后台時,key值為datas_del[],后面多了一個[]
        data:{datas_del:datas_del},
        dataType:'json',
        success:function(response,stutas,xhr){
          alert(response.sts);
          //alert(stutas);
        },
        error:function(xhr,errorText,errorStatus){
          alert(xhr.status+' error: '+xhr.statusText);
        },
        timeout:500
    }); 

 Select說明:

1.獲取select 選中的 text:
 $("#cusChildTypeId").find("option:selected").text();
 $("#cusChildTypeId option:selected").text()

2.獲取select選中的 value:
 $("#ddlRegType ").val();

3.獲取select選中的索引:
      $("#ddlRegType ").get(0).selectedIndex;

4.得到select項的個數
   
 $("#cusChildTypeId").get(0).options.length

5.設置select 選中的索引:
     $("#cusChildTypeId").get(0).selectedIndex=index;//index為索引值

6.設置select 選中的value:
    $("#cusChildTypeId").attr("value","Normal");
    $("#cusChildTypeId").val("Normal");
    $("#cusChildTypeId").get(0).value = "Normal";

7.設置select 選中的text:
 1>.var count=$("#cusChildTypeId").get(0).options.length;
     for(var i=0;i<count;i++)  
         {           
  if($("#cusChildTypeId").get(0).options.text == text)  
         {  
             $("#cusChildTypeId").get(0).options.selected = true;
             break;  
         }  
        }

 2>.$("#cusChildTypeId").val(text);
    $("#cusChildTypeId").change();

8.向select中添加一項,顯示內容為text,值為value
   
 $("#cusChildTypeId").get(0).options.add(new Option(text,value));

9.刪除select中值為value的項 
        var count = $("#cusChildTypeId").size();           
        for(var i=0;i<count;i++)   
        {   
            if($("#cusChildTypeId").get(0).options[i].value == value)   
            {   
                $("#cusChildTypeId").get(0).remove(i);   
                break;   
            }
        }

10.清空 Select:
 1>. $("#cusChildTypeId").empty();
 2>. $("#cusChildTypeId").get(0).options.length = 0;   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM