ajax相关知识 笔记


1、ajax小试:传递一个数组或字典到网页,由json处理,再显示出来

views.py:

from django.http import HttpResponse
import json
 
def ajax_list(request):
    a = list(range(100))
    return HttpResponse(json.dumps(a), content_type='application/json')
 
def ajax_dict(request):
    name_dict = {'twz': 'Love python and Django', 'zqxt': 'I am teaching Django'}
    return HttpResponse(json.dumps(name_dict), content_type='application/json')

 

 修改代码,使用JsonResponse:

 使用JsonResponse时,后端已经dumps,不需要再序列化成字符串;传到前端后,浏览器会自动进行反序列化,因此也不需要再通过parse再反序列化成对象(本身已反序列化成对象)

from django.http import JsonResponse
 
def ajax_list(request):
    a = list(range(100))
    return JsonResponse(a, safe=False)
 
def ajax_dict(request):
    name_dict = {'twz': 'Love python and Django', 'zqxt': 'I am teaching Django'}
    return JsonResponse(name_dict)

 

 urls.py:

    path('ajax_list/', views.ajax_list, name='ajax_list'),
    path('ajax_dict/', views.ajax_dict, name='ajax_dict'),

 

前端HTML:

<!DOCTYPE html>
<html>
<body>

<div id="dict">Ajax 加载字典</div>
<p id="dict_result"></p>

<div id="list">Ajax 加载列表</div>
<p id="list_result"></p>

<script src="/static/jquery-3.2.1.js"></script>
<script>
    $("#dict").click(function () {
        $.ajax({
            url:{% url 'ajax_dict' %},
            type:"GET",
            dataType:"json",
            success:function (data) {

                $("#list_result").html(data.twz);
                console.log(data)

            }
        })
    })

</script>
</body>
</html>

 

2、jQuery ajax 常用参数 

 红色标记参数都是比较重要的,几乎每个ajax请求都会用到这几个参数

$.ajax({
    url: "test.html",  //ajax请求地址
    cache: false,//(默认: true,dataType为script和jsonp时默认为false)设置为 false 将不缓存此页面,建议使用默认
    type:"GET",//请求方式 "POST" 或 "GET", 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。
    dataType:"json",    //根据返回数据类型可以有这些类型可选:xml html script json jsonp text
    //发送到服务器的数据,可以直接传对象{a:0,b:1},如果是get请求会自动拼接到url后面,如:&a=0&b=1
    //如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 "&foo=bar1&foo=bar2"。
    data:{},
    //发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。这是一个 Ajax 事件。如果返回false可以取消本次ajax请求。
    beforeSend:function(xhr){
        //this 默认为调用本次AJAX请求时传递的options参数
    },
    //context这个对象用于设置ajax相关回调函数的上下文。也就是说,让回调函数内this指向这个对象(如果不设定这个参数,那么this就指向调用本次AJAX请求时传递的options参数)。
    //比如指定一个DOM元素作为context参数,这样就设置了success回调函数的上下文为这个DOM元素。
    context: document.body,
    //请求成功后的回调函数
    success: function(data,textStatus){
        //this 调用本次AJAX请求时传递的options参数 ,如果设置context来改变了this,那这里的this就是改变过的
    },
    //请求失败时调用此函数。有以下三个参数:XMLHttpRequest 对象、错误信息、(可选)捕获的异常对象。
    //如果发生了错误,错误信息(第二个参数)除了得到null之外,还可能是"timeout", "error", "notmodified" 和 "parsererror"。
    error:function(XMLHttpRequest, textStatus, errorThrown){
        // 通常 textStatus 和 errorThrown 之中
        // 只有一个会包含信息
        // this 调用本次AJAX请求时传递的options参数
    },
    //请求完成后回调函数 (请求成功或失败之后均调用)。参数: XMLHttpRequest 对象和一个描述成功请求类型的字符串
    complete:function(XMLHttpRequest, textStatus) {
        //this 调用本次AJAX请求时传递的options参数
    },
    //一组数值的HTTP代码和函数对象,当响应时调用了相应的代码。例如,如果响应状态是404,将触发以下警报:
    statusCode:{
        404:function(){
            alert('404,页面不存在');
        }
    }
});
ajax

 

ajax 发送get/post请求,数据返回为json类型:

# get
$.ajax({
    type: "GET",
    url: "page.py",
    dataType:'json',
    data: {id:1001},  #也可以是字符串链接"id=1001",建议用对象
    success: function(data){
        console.log("返回的数据: " + data );
    }
});

# post
$.ajax({
    type: "POST",
    url: "page.py",
    dataType:'json',
    data: {name:"张三",sex:1},   # 也可以是字符串链接"name=张三&sex=1",建议用对象
    success: function(data){
        #实际操作的时候,返回的json对象中可能会有成功错误的判断标记,所以可能也需要判断一下
        console.log("返回的数据: " + data );
    }
});

 

简写:ajax 发送get/post请求,数据返回为json类型

  其实就是对ajax的二次封装

# $.get("请求url","发送的数据对象","成功回调","返回数据类型");
$.get("test.cgi",{ name: "John", time: "2pm" },
   function(data){
      alert("Data Loaded: " + data);
},'json');


# $.get("请求url","发送的数据对象","成功回调","返回数据类型");
$.post("test.cgi",{ name: "John", time: "2pm" },
   function(data){
      alert("Data Loaded: " + data);
},'json');

 

3、jquery ajax经常用到的一个工具函数

 ajax提交数据的时候,通常是提交一个表单,所以,序列化表单数据就非常有用,如:$("form").serialize()

//完整实例如:(表单html结构不在写)
    $("form").on("submit",function(){
        var url = this.action;   //可以直接取到表单的action
        var formData = $(this).serialize();
        $.post(url,formData,
            function(data){
                //返回成功,可以做一个其他事情
                console.log(data);
            },'json');

        //阻止表单默认提交行为
        return false
    })

 

ajax实例-登录

views:

using System;  
using System.Collections.Generic;  
using System.Web;  
using System.Web.Services;  
using System.Web.SessionState;  
using PLA.BLL;  
using PLA.Model;  
using Web.App_Code;  
  
namespace Web.Ajax  
{  
    [WebService(Namespace = "http://tempuri.org/")]  
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
    public class LoginHandler : IHttpHandler,IRequiresSessionState   
    {  
        public void ProcessRequest(HttpContext context)  
        {  
            context.Response.ContentType = "text/plain";  
            string username = context.Request["username"];  
            string password = context.Request["password"];  
  
            UserBLL userBLL = new UserBLL();  
            //check if the user is registered  
            if (!userBLL.GetUserRegister(username))  
            {  
                context.Response.Write("unregistered");  
            }//check if the user is frozen  
            else if (!userBLL.CheckUserBanStatusByEmail(username))  
            {  
                context.Response.Write("frozen");  
            }  
            else  
            {  
                LoginBLL loginBLL = new LoginBLL();  
                //check if the username and password is right  
                bool flag = loginBLL.ValidateLogin(username, MD5Helper.getMd5Hash(password), null);  
                if (flag)  
                {  
                    UserInfo user = userBLL.GetUserInfoByEmail(username);  
                    context.Session["UID"] = user.U_ID;  
                    context.Session["Email"] = user.U_Email;  
                    context.Response.Write("success");  
                }  
                else  
                {  
                    context.Response.Write("fail");  
                }  
            }  
        }  
  
        public bool IsReusable  
        {  
            get  
            {  
                return false;  
            }  
        }  
    }  
}  
View Code

 

html:

 login.html:

<head>  
    <title>登录</title>  
    <mce:script src="js/jquery-1.5.2.js" mce_src="js/jquery-1.5.2.js" type="text/javascript"></mce:script>  
    <mce:script src="js/login.js" mce_src="js/login.js" type="text/javascript"></mce:script>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <div id="background">  
            <div id="loginBox">  
                <span id="title">登录</span>  
                <div id="LoginMessage">  
                    用户名:  
                    <input id="txtUser" type="text" maxlength="25" class="txtbox" />  
                    <br />  
                    密 码:  
                    <input id="txtPassword" type="password" maxlength="25" class="txtbox" />  
                    <br />  
                    <center>  
                        <div id="loading">  
                            <img src="images/loading.gif" mce_src="images/loading.gif" alt="login"/></div>  
                        <input id="btnLogin" type="image" src="images/login.gif" mce_src="images/login.gif"/>  
                    </center>  
                </div>  
            </div>  
        </div>  
    </div>  
    </form>  
</body> 
login.html

 

 login.js:

var email_str = /^(?:[a-z/d]+[_/-/+/.]?)*[a-z/d]+@(?:([a-z/d]+/-?)*[a-z/d]+/.)+([a-z]{2,})+$/i; //Email regular expression  
  
$(document).ready(function() {  
    $("#btnLogin").click(function() {  
        var username = $("#txtUser").val();  
        var password = $("#txtPassword").val();  
        if (username == "" || password == "") {//check if the input is legal  
            alert("用户名和密码不可以为空!");  
            return false;  
        }  
        else if (!email_str.test(username)) {//check if email is legal  
            alert("邮件地址格式不正确!");  
            return false;  
        } else {  
            $.ajax({  
                type: "POST",  
                url: "/Ajax/LoginHandler.ashx", //event handler url  
                data: "username=" + escape($('#txtUser').val()) + "&password=" + escape($('#txtPassword').val()),//发送ajax请求  
                beforeSend: function() {  
                    $("#loading").css("display", "block"); //show loading  
                    $("#btnLogin").css("display", "none"); //hide login button  
                },  
                success: function(msg) {  
                    $("#loading").hide(); //hide loading  
                    if (msg == "unregistered") {  
                        alert("对不起,该用户未注册!");//user is unregistered  
                    }  
                    if (msg == "frozen") {  
                        alert("对不起,该用户已被冻结!");//user id frozen  
                    }  
                    if (msg == "fail") {  
                        alert("对不起,用户名或密码错误!"); //login failed  
                    }  
                    if (msg == "success") {  
                        parent.document.location.href = "manage.aspx"; //login successfully  
                    }  
                },  
                complete: function(data) {  
                    $("#loading").css("display", "none"); //hide loading  
                    $("#btnLogin").css("display", "block"); //show login  
                }  
            });  
        }  
        return false; //stop client continue submit  
    }  
);  
}); 
login.js

 结:ajax 参数列表:

   

参数名 类型 描述
url String (默认: 当前页地址) 发送请求的地址。
type String (默认: "GET") 请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。
timeout Number 设置请求超时时间(毫秒)。此设置将覆盖全局设置。
async Boolean (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
beforeSend Function 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。
function (XMLHttpRequest) {
this; // the options for this ajax request }
cache Boolean (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息。
complete Function 请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。
function (XMLHttpRequest, textStatus) {
this; // the options for this ajax request }
contentType String (默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。
data Object,
String
发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。
dataType String

预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:

"xml": 返回 XML 文档,可用 jQuery 处理。

"html": 返回纯文本 HTML 信息;包含 script 元素。

"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。

"json": 返回 JSON 数据 。

"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

error Function (默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。
function (XMLHttpRequest, textStatus, errorThrown) {
// 通常情况下textStatus和errorThown只有其中一个有值 this; // the options for this ajax request }
global Boolean (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件
ifModified Boolean (默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。
processData Boolean (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
success Function 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request }

 

demo(部分):获取博客园首页的文章题目

$.ajax({

type: "get",

url: "http://www.cnblogs.com/rss",

beforeSend: function(XMLHttpRequest){

//ShowLoading();
},
success: function(data, textStatus){

$(".ajax.ajaxResult").html("");

$("item",data).each(function(i, domEle){

$(".ajax.ajaxResult").append("<li>"+$(domEle).children("title").text()+"</li>");

});

},

complete: function(XMLHttpRequest, textStatus){

//HideLoading();
},
error: function(){

//请求出错处理
}
});
demo

 

(新增)使用ajax提交POST请求,获取CSRF验证的三种方式:

  注意:使用ajax提交POST请求,页面上必存csrf_token。存在csrf_token 的两种方式:

# 方式一:在页面中直接加入{% csrf_token  %}

# 方式二:不采用方式一时,需要在views.py 中引人:from django.views.decorators.csrf import ensure_csrf_cookie ,再将ensure_csrf_cookie加在视图上  保证返回的响应有cookie

 获取CSRF验证的三种方式:

 方式一:

# 页面中使用:{% csrf_token %}

$('#b1').click(function () {
                $.ajax({
                    url: '/csrf_test/',
                    type: 'post',
                    data: {
                        csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),  # 获取csrf_token
                        name: nan',
                        age: '73',
                    },
                    success: function (res) {
                        console.log(res);


                    }
                })
            });

 

 方式二:

# 同方式一,需要存在csrf_token ,在请求头设置csrf认证

$('#b1').click(function () {
                $.ajax({
                    url: '/csrf_test/',
                    type: 'post',
                    headers: {"X-CSRFToken": $('[name="csrfmiddlewaretoken"]').val()},
                    data: {
                        name: 'nan',
                        age: '73',

                    },
                    success: function (res) {
                        console.log(res);
                    }
                })
            });

 方式三:全局配置,建议采用这种

# 全局配置,需确保有cookie,csrf_token认证从cookie中取值。将下述代码复制到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);
    }
  }
});

 

 

posted on 2018-09-19 21:31  Eric_nan  阅读(170)  评论(0)    收藏  举报