Ajax进阶之原生js与跨域jsonp

时间:2024-05-30 19:34:38

什么是Ajax?

两个数求和:

用Jquery和数据用json格式

viws函数:

from django.shortcuts import render,HttpResponse

# Create your views here.

def index(request):

    return render(request,"sum_two.html")

import json
def sendAjax(request): print(request.body)
print(request.GET)
print(request.POST) # json的数据放在body中,用时需要先转下接着
data=request.body.decode("utf8") data=json.loads(data)
print(data) num1=data.get("num1")#这是字典形式用get
print(num1,"第一个")
num2=data.get("num2")
print(num2, "第2个") ret=int(num1)+int(num2) return HttpResponse(ret)

html函数

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<h1>INDEX</h1> <input type="text" class="num1">+<input type="text" class="num2">=<input type="text" class="ret">
<button>send Ajax</button>
{% csrf_token %} <form action="" method=""></form> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script>
<script>
// 基于jquery实现 $("button").click(function () { $.ajax({
url:"/sendAjax/",
type:"POST",<!--请求方法是post是就要用csrf_token-->
headers:{"X-CSRFToken":$.cookie('csrftoken')},<!--最好用这个方法-->
data:JSON.stringify({<!--变成json数据格式 里面数据键可以用引号也可以不用-->
num1:$(".num1").val(),
num2:$(".num2").val()
}),
contentType:"application/json",<!--客户端给服务器端提交数据的格式-->
success:function (data) {
console.log(data);
$(".ret").val(data)<!--数据赋值给求和的值-->
}
})
}) </script>
</body>
</html>

原生js发送数据(数据格式是一般类型的)

views函数

from django.shortcuts import render,HttpResponse

# Create your views here.

def index(request):

    return render(request,"sum_two.html")

import json
def sendAjax(request): print(request.body)这里有数据
print(request.GET)#这里没有数据
print(request.POST)这里有数据 #urlencoded 普通的数据类型
num1=request.POST.get("num1")
num2=request.POST.get("num2")
ret=int(num1)+int(num2) return HttpResponse(ret)

html函数  4步5种状态

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<h1>INDEX</h1> <input type="text" class="num1">+<input type="text" class="num2">=<input type="text" class="ret">
<button>send Ajax</button>
{% csrf_token %} {#<form action="" method=""></form>#} <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script>
<script> //基于JS实现 var ele_btn=document.getElementsByTagName("button")[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
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // (3) 发送数据
var ele_csrf=document.getElementsByName("csrfmiddlewaretoken")[0];
ele_num1=document.getElementsByClassName("num1")[0];
ele_num2=document.getElementsByClassName("num2")[0];
ele_ret=document.getElementsByClassName("ret")[0]; s1="num1="+ele_num1.value;
s2="num2="+ele_num2.value;
s3="&csrfmiddlewaretoken="+ele_csrf.value;
xmlHttp.send(s1+"&"+s2+s3); <!--请求体数据--> // (4) 回调函数 success
xmlHttp.onreadystatechange = function() {
if(this.readyState==4 && this.status==200){
ele_ret.value=this.responseText }
}; } </script>
</body>
</html>

原生js发送数据(数据格式是json)页面上只用了点击

views视图函数

from django.shortcuts import render,HttpResponse

# Create your views here.

def index(request):

    return render(request,"sum_two.html")

import json
def sendAjax(request): print(request.body)
print(request.GET)没有数据
print(request.POST)没有数据 # json的数据放在body中,用时需要先转下接着
data=request.body.decode("utf8") data=json.loads(data)
print(data)
print(data["name"])
print(data["age"]) return HttpResponse("ok")

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<h1>INDEX</h1> <input type="text" class="num1">+<input type="text" class="num2">=<input type="text" class="ret">
<button>send Ajax</button>
{% csrf_token %} {#<form action="" method=""></form>#} <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script>
<script> //======================================================json var ele_btn=document.getElementsByTagName("button")[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); // (3) 发送数据 xmlHttp.send('{"name":"yuan","age":12}') ; // 请求体数据 // (4) 回调函数 success
xmlHttp.onreadystatechange = function() {
if(this.readyState==4 && this.status==200){
console.log(this.responseText) }
}; } </script>
</body>
</html>

跨域jsonp

解决跨域用种方向:

一:就是Access-Control-Allow-Origin

二:Jsonp

建立两个项目

项目1:

htmls:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<h2>项目1</h2>
<button>send ajax</button>
<span class="ky">kuayu</span>
<p><span class="getJsonp">getJsonp</span></p>
<p><span class="final_ajax">final_ajax</span></p>
<p><span class="jiangxiTV">jiangxiTV</span></p>
<a href="http://127.0.0.1:8111/ajax_send2/">跳转</a>
<hr>
<div class="show_list"> </div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script> <script> //这种方法就会产生跨站请求被阻止的
$("button").click(function () { $.ajax({
url:"http://127.0.0.1:8111/ajax_send2/",
success:function (data) {
console.log(data)
}
}) });
function foo(arg) {
console.log(arg)
} // 动态生成script标签 function add_scipt(url) {
var ele_script=$("<script>"); //
ele_script.attr("src",url);//添加属性
ele_script.attr("id","dy_tag");//添加属性
$("body").append(ele_script);<!--添加用append-->
$("#dy_tag").remove()
}
$(".ky").click(function () { add_scipt("http://127.0.0.1:8111/ajax_send2/?callbacks=foo") }); // jquery: getJsonp这个回调函数是匿名函数 $(".getJsonp").click(function () { $.getJSON("http://127.0.0.1:8111/ajax_send2/?callbacks=?",{"name":123},function (data) {
console.log(data)
})
}); // final_ajax用jquery实现时返回的数据不用反序列化 $(".final_ajax").click(function () { $.ajax({
url:"http://127.0.0.1:8111/ajax_send2/",
dataType:"jsonp",
jsonp: 'callbacks',
success:function (data) {
console.log(data)
}
}) }) // 跨域请求实例请求电视台的信息 返回信息不用发序列化
$(".jiangxiTV").click(function () { $.ajax({
url:"http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'list',
success:function (data) {
console.log(data.data); // [{},{},{},{},{},{}]
week_list=data.data; $.each(week_list,function (i,j) {<!--循环的时候的用each-->
console.log(i,j); // 1 {week: "周一", list: Array(19)}
s="<p>"+j["week"]+"列表</p>";<!--对象可以用.或者字典的取值方式都可以-->
$(".show_list").append(s); $.each(j.list,function (k,v) { // {time: "0030", name: "通宵剧场六集连播", link: "http://www.jxntv.cn/live/jxtv2.shtml"}
a="<p><a href='"+v.link+"'>"+v.name+"</a></p>";<!--用拼接的方式-->
$(".show_list").append(a);
})
}) }
}) }) </script> </body>
</html>

views:

from django.shortcuts import render,HttpResponse

# Create your views here.
def index(request): return render(request,"index.html") def ajax_send(request):
print("")
return HttpResponse("项目1")

urls

from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
]

项目2:

htmls:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title> </head>
<body>
<h2>项目2</h2>
<button>send ajax</button> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script> <script>
$("button").click(function () { $.ajax({
url:"/ajax_send2/",
success:function (data) {
console.log(data)
}
}) })
</script>
</body>
</html>

views:

from django.shortcuts import render,HttpResponse

# Create your views here.

def index(request):

    return render(request,"index.html")

def ajax_send2(request):

    func_name=request.GET.get("callbacks")
import json
print(222222222) print(request.GET)
print(func_name) # jQuery32104784307525424374_1512015579023 s={"name":"egon","age":123}
return HttpResponse("%s(%s)"%(func_name,json.dumps(s)))#这个用的是匿名函数 def foo(): # return HttpResponse("list({})")
return HttpResponse("ok")

urls:

from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^ajax_send2/', views.ajax_send2), ]
                dataType:"jsonp",            //必须有,告诉server,这次访问要的是一个jsonp的结果。
jsonp: 'callbacks', //jQuery帮助随机生成的:callbacks="wner"

用jsonp的实例(一个电视台信息的请求)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<h2>项目1</h2>
<button>send ajax</button>
<span class="ky">kuayu</span>
<p><span class="getJsonp">getJsonp</span></p>
<p><span class="final_ajax">final_ajax</span></p>
<p><span class="jiangxiTV">jiangxiTV</span></p>
<a href="http://127.0.0.1:8011/ajax_send2/">跳转</a>
<hr>
<div class="show_list"> </div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script> <script> //这种方法就会产生跨站请求被阻止的
$("button").click(function () { $.ajax({
url:"http://127.0.0.1:8111/ajax_send2/",
success:function (data) {
console.log(data)
}
}) });
function foo(arg) {
console.log(arg)
} // 动态生成script标签 function add_scipt(url) {
var ele_script=$("<script>"); //
ele_script.attr("src",url);//添加属性
ele_script.attr("id","dy_tag");//添加属性
$("body").append(ele_script);
$("#dy_tag").remove()
}
$(".ky").click(function () { add_scipt("http://127.0.0.1:8111/ajax_send2/?callbacks=foo") }); // jquery: getJsonp $(".getJsonp").click(function () { $.getJSON("http://127.0.0.1:8111/ajax_send2/?callbacks=?",{"name":123},function (data) {
console.log(data)
})
}); // final_ajax用jquery实现时返回的数据不用反序列化 $(".final_ajax").click(function () { $.ajax({
url:"http://127.0.0.1:8111/ajax_send2/",
dataType:"jsonp",
jsonp: 'callbacks',
success:function (data) {
console.log(data)
}
}) }) // 跨域请求实例请求电视台的信息 返回信息不用发序列化
$(".jiangxiTV").click(function () { $.ajax({
url:"http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'list',
success:function (data) {
console.log(data.data); // [{},{},{},{},{},{}]
week_list=data.data; $.each(week_list,function (i,j) {<!--循环的时候的用each-->
console.log(i,j); // 1 {week: "周一", list: Array(19)}
s="<p>"+j["week"]+"列表</p>";<!--对象可以用.或者字典的取值方式都可以-->
$(".show_list").append(s); $.each(j.list,function (k,v) { // {time: "0030", name: "通宵剧场六集连播", link: "http://www.jxntv.cn/live/jxtv2.shtml"}
a="<p><a href='"+v.link+"'>"+v.name+"</a></p>";<!--用拼接的方式-->
$(".show_list").append(a);
})
}) }
}) }) </script> </body>
</html>