JSON和ajax


1.JSON

1.JSON指的是JavaScript對象表示法,是文本數據交換格式
2.在使用json對象時需要注意:
{ name: "張三", 'age': 32 }  // 屬性名必須使用雙引號
[32, 64, 128, 0xFFF] // 不能使用十六進制值
{ "name": "張三", "age": undefined }  // 不能使用undefined
{ "name": "張三",
  "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),
  "getName":  function() {return this.name;}  // 不能使用函數和日期對象
}
3.JavaScript中關於JSON對象和字符串轉換的兩個方法:
JSON.parse():用於將一個JSON字符串轉換成JavaScript對象
JSON.parse('{"name":"Q1mi"}');
JSON.stringify():用於將JavaScript轉換成JSON字符串
4.在python中,將其他數據類型轉換成字符串使用json.dumps和json.loads()
json.dumps轉換完的字符串類型的字典中的字符串是由""表示的
import json
dic={'name':'jerd','age':18}
ret=json.dumps(dic)
print(ret,type(ret)) #{"name": "jerd", "age": 18} <class 'str'>
要用json的loads功能處理的字符串類型的字典中的字符串必須由""表示
# dic1="{'name':'jerd','age':18}"  #報錯
dic1='{"name":"jerd","age":18}'
ret=json.loads(dic1)
print(ret,type(ret))  #{'name': 'jerd', 'age': 18} <class 'dict'>

2.AJAX

1.同步交互和異步交互的概念:
同步交互:客戶端發出一個請求,粗腰等待服務器響應結束后,才能發送第二個請求
異步交互:客戶端發出一個請求后,無需等待服務器響應結束,就可以發出第二個請求
2.AJAX翻譯成中文就是“異步Javascript和XML”,AJAX除了異步的特點外,還有一個就是:瀏覽器頁面局部刷新;
(這一特點給用戶的感受是在不知不覺中完成請求和響應過程)
3.AJAX的優點:
AJAX使用JavaScript技術向服務器發送異步請求;
AJAX請求無須刷新整個頁面;
因為服務器響應內容不再是整個頁面,而是頁面中的部分內容,所以AJAX性能高
4.在jQuery中使用AJAX
1.首先要導入<script src="/static/jquery-3.3.1.js"></script>
2.綁定事件 $("#b1").on("click",function(){})
3.在事件中寫入要操作的事:$.ajax()
<script src="/static/jquery-3.3.1.js"></script>
<script>
    $("#b1").on("click",function(){
        var i1=$("#i1").val();
        var i2=$("#i2").val();
        $.ajax(
            {
                url:"/ajax_add/",
                type:"get",
                data:{"i1":i1,"i2":i2},  如果字典中有可變數據類型,后台就接收不到,需要序列化 data:{"i1":i1,"i2":JSON.stringify([1,12,3])}
                success:function(arg){
                // 把返回的結果(arg)填充到 id是i3的input框中
                  $("#i3").val(arg);
                }
            }
        )
        }
    );
def ajax_add(request):
    i1 = int(request.GET.get("i1"))
    i2 = int(request.GET.get("i2"))
    ret=i1+i2
    return HttpResponse(ret)
View Code
5.在ajax中,請求時ajax發出的,不是瀏覽器發出的。服務端回響應后,應有js代碼處理
location.href="http://www.baidu.com" 當前所在網址,可通過設置,跳到指定的網址
6.在ajax中使用post時,會有csrf校驗,需要設置csrf_token
###方法一:
1.將{ %csrf_token %}寫下input標簽前面
2.在ajax中取到csrf中input的值 var csrfToken = $("[name='csrfmiddlewaretoken']").val();
3.加到傳輸的數據中 data:{"i1":i1,"i2":i2,'csrfmiddlewaretoken':csrfToken}
{% csrf_token %}
<input type="text" id="i1">+
<input type="text" id="i2">=
<input type="text" id="i3">
<input type="button" value="ajax_post請求" id="b3">
 $("#b3").on("click",function(){
        var i1=$("#i1").val();
        var i2=$("#i2").val();
        var csrftoken=$("[name='csrfmiddlewaretoken']").val();
        {# 往后台提交數據  #}
        $.ajax(
            {
                url:"/ajax_add/",
                type:"post",
                data:{"i1":i1,"i2":i2,"csrfmiddlewaretoken":csrftoken},
                success:function(arg){
                // 把返回的結果填充到 id是i3的input框中
                  $("#i3").val(arg);
                }
            }
        )
        }
    );
    ##方法二:通過獲取返回的cookie中的字符串 放置在請求頭中發送。不用寫{% csrf_token %}
自定義一個js文件如setupajax.js,寫入以下代碼。在html中引入js文件
 function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});

3.AJXA中的datetype和traditional,contentType,async參數

$("#b1").on("click", function () {
        $.ajax({
            url: "/test/",
            type: "post",
            dataType: "json", #不需要手動反序列話數據 var data = JSON.parse(data); 
            traditional: true, #如果不加這個參數,data中[1,2,3]就要序列化"sb":JSON.stringify([1,12,3])
            data: {"name": "jerd", "sb":[1,2,3]},  
            success: function (data) {
                // 如果后端返回來的數據經過了序列化,需要把數據反序列化成JS中的對象
                // var data = JSON.parse(data); 
                if (data.status === 0){
                    // 這次請求成功
                    alert(data.data);
                }else {
                    // 請求出錯
                    alert(data.error);
                }
            }
        })
    });
import json
def test(request):
    if request.method == "POST":
        name = request.POST.get("name")
        sb = request.POST.getlist("sb")
        print(name)
        print(sb, type(sb))
        ret = {
            "status": 0,
            "data": [
                {"name": "jerd", "age": 18},
                {"name": "xiaohei", "age": 28},
            ]
            "status": 1,
            "error": "用戶名已被注冊!"
        }
        ret_str = json.dumps(ret)
        return HttpResponse(ret_str)
    return render(request, "test.html")
View Code

用戶注冊校驗

當鼠標移出輸入框后,就檢驗用戶名是否可以使用
HTML中代碼:
<p>
   <input type="text" id="i1" name="name">
</p>
// 找到 i1 標簽,綁定失去焦點的事件
    $("#i1").blur(function () {
    ##在輸入框中個輸入時就提示
    # $("#i1").on("input", function () {
        // 取到input框的值(dom對象)console.log(this);
        var $i1Ele = $(this);
        var name = $i1Ele.val();
        // 去掉i1后面的提示語
       $i1Ele.next("span").remove
        // 利用ajax請求偷偷發到后端
        $.ajax({
            url: "/check_user/",
            type: "post",
            data: {"name": name},
            datatype: "json",
            success:function (arg) {
                // 創建span標簽,作為提示語
                var spanEle=document.createElement("span");
                $(spanEle).css("color","red")  提示語設置為紅色
                spanEle.innerText=arg;
                // 把span標簽放到i1的后面
                $i1Ele.after(spanEle)
            }
        })
    })
views函數
def check_user(request):
    if request.method == "POST":
        name = request.POST.get("name")
        # 去數據庫中查詢用戶名是否已經被注冊
        ret = models.UserInfo.objects.filter(name=name)
        if ret:
            # 用戶名已經存在
            msg = "用戶名已被注冊!"
        else:
            msg = "用戶名可用"

        return HttpResponse(msg)
2.不再手動再輸入框后面加標簽,提前在輸入框后面加個標簽,值為空
<p>
   <input type="text" id="i1" name="name">
    <span id="e1"></span>
</p>
 $("#i1").blur(function () {
        var $i1Ele = $(this);
        var name = $i1Ele.val();
        $("#e1").text("");
        // 利用ajax請求偷偷發到后端
        $.ajax({
            url: "/check_user/",
            type: "post",
            data: {"name": name},
            datatype: "json",
            success:function (arg) {
                // 把span標簽放到i1的后面
                 $("#e1").text(arg).css("color", "red");
            }
        })
    })
View Code

ajax在全局環境中是異步模式的,async講的是ajax請求內部的同異步。 分別有true和false。true表示是異步模式,false表示同步模式。
對於同步模式,如果ajax發出請求(send方法調用后),后續還有代碼執行,此時如果服務器響應不及時(也就是此時ajax的請求代碼還沒有全部執行完成),后續的代碼不會執行(此時頁面出現假死狀態,此時也不用考慮代碼的執行順序)。此時就會出現阻塞狀態。 
對於異步模式,一般多用異步模式。如果ajax執行完send后,后續還有代碼需要執行,此時服務器響應不夠及時,后續的代碼還是會繼續執行。不會出現阻塞現象 
既然異步比較好,那為什么會有同步這個選項呢。答案是,因為如果ajax執行完send后,后續的代碼是有關於響應結果的處理,那如果是異步請求,則如果此時服務器的響應結果還沒回來,那么后續有關於響應結果的處理就會出現錯誤(return null)。此時是一定要用同步的。

 

 

使用contentType和不使用contentType

 

4.發送請求的方式

1.直接在地址欄輸入url回車 GET請求
2.a標簽 GET請求
3.form表單 GET/POST請求
4.AJAX GET/POST請求

5.SweetAlert插件 刪除提示示例

$(".btn-danger").on("click", function () {
  swal({
    title: "你確定要刪除嗎?",
    text: "刪除可就找不回來了哦!",
    type: "warning",
    showCancelButton: true,
    confirmButtonClass: "btn-danger",
    confirmButtonText: "刪除",
    cancelButtonText: "取消",
    closeOnConfirm: false
    },
    function () {
      var deleteId = $(this).parent().parent().attr("data_id");
      $.ajax({
        url: "/delete_book/",
        type: "post",
        data: {"id": deleteId},
        success: function (data) {
          if (data.status === 1) {
            swal("刪除成功!", "你可以准備跑路了!", "success");
          } else {
            swal("刪除失敗", "你可以再嘗試一下!", "error")
          }
        }
      })
    });
})
使用birthday=models.DateField(auto_now_add=True),如果在SQLite中直接添加數據
時間的格式是146575575,如果是通過命令創建顯示2018-5-06
View Code
 
        

ajax示例:

{% csrf_token %}
<input type="text" id="i1">+
<input type="text" id="i2">=
<input type="text" id="i3">
{#類型為button#}
<input type="button" value="ajax提交" id="b1">
<input type="button" value="ajax跳轉" id="b2">
<input type="button" value="ajax_post請求" id="b3">
<input type="button" value="cookie_post請求" id="b4">
<script src="/static/jquery-3.3.1.js"></script>
<script src="/static/setupajax.js"></script>
<script>
   {# 簡單的運算示例   #}
    $("#b1").on("click",function(){
        var i1=$("#i1").val();
        var i2=$("#i2").val();
        {# 往后台提交數據  #}
        $.ajax(
            {
                url:"/ajax_add/",
                type:"get",
                data:{"i1":i1,"i2":i2},
                success:function(arg){
                // 把返回的結果填充到 id是i3的input框中
                  $("#i3").val(arg);
                }
            }
        )
        }
    );
      $("#b2").on("click", function () {
        $.ajax({
            url: "/test/",
            type: "get",
            success:function (a) {
                // a是網址,跳轉到制定的網址
                location.href = a;
                // alert(a);
                // 在頁面上創建一個標簽
                //var imgEle = document.createElement("img");
                //imgEle.src = a; 制定圖片的地址
                // 把創建的img標簽添加到文檔中
                //$("#b2").after(imgEle);
            }
        })
    });
    $("#b3").on("click",function(){
        var i1=$("#i1").val();
        var i2=$("#i2").val();
        var csrftoken=$("[name='csrfmiddlewaretoken']").val();
        {# 往后台提交數據  #}
        $.ajax(
            {
                url:"/ajax_add/",
                type:"post",
                data:{"i1":i1,"i2":i2,"csrfmiddlewaretoken":csrftoken},
                success:function(arg){
                // 把返回的結果填充到 id是i3的input框中
                  $("#i3").val(arg);
                }
            }
        )
        }
    );
{#   獲取cookie字符串 #}
     $("#b4").on("click",function(){
        var i1=$("#i1").val();
        var i2=$("#i2").val();
        {# 往后台提交數據  #}
        $.ajax(
            {
                url:"/ajax_add/",
                type:"post",
                data:{"i1":i1,"i2":i2},
                success:function(arg){
                // 把返回的結果填充到 id是i3的input框中
                  $("#i3").val(arg);
                }
            }
        )
        }
    );
</script>
HTML
from django.shortcuts import render,HttpResponse

# Create your views here.
def index(request):
    return render(request,"index.html")
def ajax_add(request):
    # i1 = int(request.GET.get("i1"))
    # i2 = int(request.GET.get("i2"))
    ##post請求
    i1 = int(request.POST.get("i1"))
    i2 = int(request.POST.get("i2"))
    print(i1,i2)
    ret=i1+i2
    return HttpResponse(ret)
def test(request):
    url = "http://p7.yokacdn.com/pic/YOKA_HZP/2018-01-19/U10089P42TS1516351813_11903.jpg"
    # return HttpResponse(url)
    # return render(request, "index.html")
    #不能使用redirect
    return HttpResponse("http://www.baidu.com")
Views

刪除提示

<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
           <h3 class="panel-title">person管理</h3>
        </div>
        <div class="panel-body">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>序號</th>
                        <th>id</th>
                        <th>name</th>
                        <th>age</th>
                        <th>生日</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for person in person_list %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ person.id }}</td>
                            <td>{{ person.name }}</td>
                            <td>{{ person.age }}</td>
                            <td>{{ person.birthday|date:'Y-m-d' }}</td>
                            <td>
                                 <button class="btn btn-danger del"><i class="fa fa-trash-o">刪除</i></button>
                            </td>

                        </tr>
                    {% endfor %}

                </tbody>
            </table>
        </div>
    </div>
</div>
<script src="/static/jquery-3.3.1.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
<script src="/static/sweetalert/sweetalert.min.js"></script>
<script src="/static/setupajax.js"></script>
<script>
    $(".del").on("click",function () {
        //找到<tr>標簽
         var $trEle = $(this).parent().parent();
            //找到<tr>標簽id
        var delId = $trEle.children().eq(1).text();
     swal({
        title: "你確定要刪除嗎?",
        text: "刪除可就找不回來了哦!",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "刪除",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        showLoaderOnConfirm: true
        },function () {
           //找到<tr>標簽
              $.ajax({
                url: "/delete_person/",
                type: "post",
                data: {"id": delId},
                success: function (data) {
                  if (data === "1") {
                    swal("刪除成功!", "success");
                  } else {
                    swal("刪除失敗", "error")
                  }
                  //點擊確認后,頁面上就清除這個,不使用的話需要刷新才能看到效果
                  $trEle.remove();
                }
              })
            });

        
    })
</script>
HTML
from ajax_test import models
def person(request):
    ###自己序列化##
    ret = models.Person.objects.all()
    person_list = []
    for i in ret:
        person_list.append({"name": i.name, "age": i.age,"birthday":i.birthday})
    import json
    s = json.dumps(person_list)
    ##使用django模塊序列化##
    # from django.core import serializers
    # s = serializers.serialize("json", ret)
    # return HttpResponse(s)

    return HttpResponse(s)
####刪除提示示例##
def person_list(request):
    ret = models.Person_list.objects.all()
    print(66)
    print(ret[1].birthday)
    return render(request,"person_list.html",{"person_list":ret})
def delete_person(request):
    import time
    time.sleep(3)
    id=request.POST.get("id")
    models.Person_list.objects.filter(id=id).delete()
    return HttpResponse("1")
Views

 

 


 


免責聲明!

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



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