Ajax进阶之原生js与跨域jsonp
什么是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>
Ajax进阶之原生js与跨域jsonp的更多相关文章
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
一.浏览器同源策略 首先我们需要了解一下浏览器的同源策略,关于同源策略可以仔细看看知乎上的一个解释.传送门 总之:同协议,domain(或ip),同端口视为同一个域,一个域内的脚本仅仅具有本域内的权限 ...
- 实现jquery.ajax及原生的XMLHttpRequest跨域调用WCF服务的方法
关于ajax跨域调用WCF服务的方法很多,经过我反复的代码测试,认为如下方法是最为简便的,当然也不能说别人的方法是错误的,下面就来上代码,WCF服务定义还是延用上次的,如: namespace Wcf ...
- JS JSOP跨域请求实例详解
JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题.这篇文章主要介绍了JS JSOP跨域请求实例详解的相关资料,需要的朋友可以参考下 ...
- 小结ajax中的同源和跨域 jsonp和cors
网上的同源和跨域一般都比较复杂,最近也稍微总结了一下: 所谓同源,是浏览器的一种安全机制,作用在于保护网页数据的安全,不同源的网页之间不允许cookie dom ajax等行为 同源的条件:1.协议相 ...
- 搞懂:前端跨域问题JS解决跨域问题VUE代理解决跨域问题原理
什么是跨域 跨域:一个域下的文档或脚本试图去请求另一个域下的资源 广义的跨域包含一下内容: 1.资源跳转(链接跳转,重定向跳转,表单提交) 2.资源请求(内部的引用,脚本script,图片img,fr ...
- js调用跨域
web aapi 初体验 解决js调用跨域问题 跨域界定 常见跨域: 同IP不同端口: http:IP:8001/api/user http:IP:8002/api/user 不同IP不同 ...
- js&jquery跨域详解jsonp,jquery并发大量请求丢失回调bug
URL 说明 是否允许通信 http://www.a.com/a.js http://www.a.com/b.js 同一域名下 允许 http://www.a.com/lab/a.js http:/ ...
- js执行跨域请求
//js执行跨域请求 var _script = document.createElement('script'); _script.type = "text/javascript" ...
- react-native debug js remotely跨域问题
react-native debug js remotely跨域问题 我们在安卓真机上调试react-native时,启用debug js remotely的时候,会出现跨域问题.这个时候我们只需要一 ...
随机推荐
- SpringBoot(4) SpringBoot热部署
热部署,就是在应用正在运行的时候升级软件,却不需要重新启动应用. 使用springboot结合dev-tool工具,快速加载启动应用 官方地址:https://docs.spring.io/sprin ...
- C#中的readonly跟const用法小结
总结一下常量和只读字段的区别: 由来: 笔者也是在看欧立奇版的<.Net 程序员面试宝典>的时候,才发现自己长久以来竟然在弄不清出两者的情况下,混用了这么长的时间.的确,const与rea ...
- Oracle入门《Oracle介绍》第一章1-2 Oracle 实例
Oracle实例:是后台进程和内存结构的集合 一.内存结构 1.Oracle 实例启动时分配系统全局区 a.数据库信息存储于SGA,由多个数据库进程共享 1.共享池是对SQL.PL/SQL程序进行语法 ...
- Idea中JDK为1.8,还提示Diamond types are not supported at this language level
project的java level 已经核实确实为8,但是IDEA里面仍然会有如下图的提示: 通过查看项目设置,发现project的java level 也是8. 然后继续检查其他模块 如modul ...
- 【IDEA&&Eclipse】3、IntelliJ IDEA 的 20 个代码自动完成的特性
在这篇文章中,我想向您展示 IntelliJ IDEA 中最棒的 20 个代码自动完成的特性,可让 Java 编码变得更加高效.对任何集成开发环境来说,代码的自动完成都是最最重要的一项功能,它根据你输 ...
- Spring基于纯注解方式的使用
经过上篇xml与注解混合方式,对注解有了简单额了解,上篇的配置方式极大地简化了xml中配置,但仍有部分配置在xml中进行,接下来我们就通过注解的方式将xml中的配置用注解的方式实现,并最终去掉xml配 ...
- 列表中文字太多 溢出使用省略号css方法
我们经常会遇到文字太多,而为了不打破原有布局,需要将多出文字用省略号代替,实现以下效果: 文字太太太太多多多啦...... 这个不多. html:这是个列表.ul/ol都行. <ul> & ...
- Spark 跑 java 示例代码
一.下载示例代码: git clone https://github.com/melphi/spark-examples.git 从示例代码中可以看到 pox中引入了 Spark开发所需要的依赖. 二 ...
- JS模拟实现数组的map方法
昨天使用map方法的时候,突然感觉一直在直接用,也没有试试是怎么实现的,本来想直接搜一篇文章盘一下子,结果没搜到合适的,好吧,那就自己来写一下子吧 今天就来实现一个简单的map方法 首先我们来看一下m ...
- JS点击按钮下载文件
通过form表单提交: 由于ajax函数的返回类型只有xml.text.json.html等类型,没有“流”类型,所以通过ajax去请求该接口是无法下载文件的,所以我们创建一个新的form元素来请求接 ...