前端之json,ajax和jsonp
json
json是 JavaScript Object Notation 的首字母缩写,单词的意思是javascript对象表示法,这里说的json指的是类似于javascript对象的一种数据格式,目前这种数据格式比较流行,逐渐替换掉了传统的xml数据格式。
javascript对象字面量:
var oMan = {
name:'tom',
age:16,
talk:function(s){
alert('我会说'+s);
}
}
json格式的数据:
{
"name":"tom",
"age":18
}
与json对象不同的是,json数据格式的属性名称需要用双引号引起来,用单引号或者不用引号会导致读取数据错误。
json的另外一个数据格式是数组,和javascript中的数组字面量相同。
["tom",18,"programmer"]
配置服务器环境-node.js的简单使用
C:\Users\username>node -v
v7.4.0 C:\Users\username>e: E:\>cd E:\Pycharm\Pycharm_save\cp15\05前端\05jQuery和js库\04jQuery第四天 E:\Pycharm\Pycharm_save\cp15\05前端\05jQuery和js库\04jQuery第四天>node server.js
Static file server running at
=> http://localhost:8888/
CTRL + C to shutdown
使用node.js运行的小型服务器文件:server.js
/*
NodeJS Static Http Server - http://github.com/thedigitalself/node-static-http-server/
By James Wanga - The Digital Self
Licensed under a Creative Commons Attribution 3.0 Unported License. A simple, nodeJS, http development server that trivializes serving static files. This server is HEAVILY based on work done by Ryan Florence(https://github.com/rpflorence) (https://gist.github.com/701407). I merged this code with suggestions on handling varied MIME types found at Stackoverflow (http://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs). To run the server simply place the server.js file in the root of your web application and issue the command
$ node server.js
or
$ node server.js 1234
with "1234" being a custom port number" Your web application will be served at http://localhost:8888 by default or http://localhost:1234 with "1234" being the custom port you passed. Mime Types:
You can add to the mimeTypes has to serve more file types. Virtual Directories:
Add to the virtualDirectories hash if you have resources that are not children of the root directory */
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888; var mimeTypes = {
"htm": "text/html",
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"js": "text/javascript",
"css": "text/css"}; var virtualDirectories = {
//"images": "../images/"
}; http.createServer(function(request, response) { var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri)
, root = uri.split("/")[1]
, virtualDirectory; virtualDirectory = virtualDirectories[root];
if(virtualDirectory){
uri = uri.slice(root.length + 1, uri.length);
filename = path.join(virtualDirectory ,uri);
} fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
console.error('404: ' + filename);
return;
} if (fs.statSync(filename).isDirectory()) filename += '/index.html'; fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
console.error('500: ' + filename);
return;
} var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
response.writeHead(200, {"Content-Type": mimeType});
response.write(file, "binary");
response.end();
console.log('200: ' + filename + ' as ' + mimeType);
});
});
}).listen(parseInt(port, 10)); console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
server.js
ajax
ajax技术的目的是让javascript发送http请求,与后台通信,获取数据和信息。ajax技术的原理是实例化xmlhttp对象,使用此对象与后台通信。ajax通信的过程不会影响后续javascript的执行,从而实现异步。
同步和异步
现实生活中,同步指的是同时做几件事情,异步指的是做完一件事后再做另外一件事,程序中的同步和异步是把现实生活中的概念对调,也就是程序中的异步指的是现实生活中的同步,程序中的同步指的是现实生活中的异步。
局部刷新和无刷新
ajax可以实现局部刷新,也叫做无刷新,无刷新指的是整个页面不刷新,只是局部刷新,ajax可以自己发送http请求,不用通过浏览器的地址栏,所以页面整体不会刷新,ajax获取到后台数据,更新页面显示数据的部分,就做到了页面局部刷新。
同源策略
ajax请求的页面或资源只能是同一个域下面的资源,不能是其他域的资源,这是在设计ajax时基于安全的考虑。特征报错提示:
XMLHttpRequest cannot load https://www.baidu.com/. No
'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
$.ajax使用方法
常用参数:
- url 请求地址
- type 请求方式,默认是'GET',常用的还有'POST'
- dataType 设置返回的数据格式,常用的是'json'格式,也可以设置为'html'
- data 设置发送给服务器的数据
- success 设置请求成功后的回调函数
- error 设置请求失败后的回调函数
- async 设置是否异步,默认值是'true',表示异步
以前的写法:
$.ajax({
url: 'js/data.json',
type: 'GET',
dataType: 'json',
data:{'aa':1}
success:function(data){
alert(data.name);
},
error:function(){
alert('服务器超时,请重试!');
}
});
新的写法(推荐):
$.ajax({
url: 'js/data.json',
type: 'GET',
dataType: 'json',
data:{'aa':1}
})
.done(function(data) {
alert(data.name);
})
.fail(function() {
alert('服务器超时,请重试!');
});
// data.json里面的数据: {"name":"tom","age":18}
jsonp
ajax只能请求同一个域下的数据或资源,有时候需要跨域请求数据,就需要用到jsonp技术,jsonp可以跨域请求数据,它的原理主要是利用了script标签可以跨域链接资源的特性。
jsonp的原理如下:
<script type="text/javascript">
function aa(dat){
alert(dat.name);
}
</script>
<script type="text/javascript" src="....../js/data.js"></script>
页面上定义一个函数,引用一个外部js文件,外部js文件的地址可以是不同域的地址,外部js文件的内容如下:
aa({"name":"tom","age":18});
外部js文件调用页面上定义的函数,通过参数把数据传进去。
json简单使用示例(在sever.js被node运行的条件下,有一个叫data.json的文件存储数据)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
url: 'data.json',
type: 'get',
dataType: 'json'
})
.done(function (dat) {
$('#username').html(dat.name);
$('#userage').html(dat.age); })
.fail(function () {
alert('服务器超时!');
})
})
</script>
</head>
<body>
<p>姓名:<span id="username"></span></p>
<p>年龄:<span id="userage"></span></p>
</body>
</html>
json简单使用示例
生鲜首页获取json数据制作欢迎用户登录
<script type="text/javascript">
$(function () {
$.ajax({
url:'js/data.json',
type:'get',
dataType:'json'
})
.done(function(dat){ $('.user_login_btn').hide(); $('.user_info em').html(dat.name); $('.user_info').show(); })
.fail(function(){
alert('服务器超时!')
})
})
</script> <body>
<!-- 页面顶部 -->
<div class="header_con">
<div class="header">
<div class="welcome fl">欢迎来到天天生鲜!</div> <div class="top_user_info fr">
<div class="user_login_btn fl">
<a href="">登录</a>
<span>|</span>
<a href="">注册</a>
</div> <div class="user_info fl">
欢迎您:<em>张三</em>
</div> <div class="user_link fl">
<span>|</span>
<a href="">我的购物车</a>
<span>|</span>
<a href="">我的订单</a>
</div>
</div>
</div>
</div>
</body>
首页获取用户信息并欢迎
jsonp的简单使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'js/data.js',
type: 'get',
dataType: 'jsonp',
jsonpCallback: 'fnback'
})
.done(function (dat) { alert(dat.name);
})
</script>
</head>
<body>
</body>
</html> //data.js
//fnback({'name':'tom'});
jsonp的简单使用
jsonp练习-360联想词获取
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8
// &format=json&fields=word&word=d $(function () {
$('#input01').keyup(function () {
var $val = $(this).val(); $.ajax({
url: 'https://sug.so.360.cn/suggest?',
type: 'get',
dataType: 'jsonp',
data: {'word': $val}
})
.done(function (data) {
//console.log(data);
// 清空元素里面的内容
$('#list01').empty(); var dat = data.s;
for (var i = 0; i < dat.length; i++) {
var $newli = $('<li>'); $newli.html(dat[i]); $newli.appendTo($('#list01'));
}
})
})
})
</script>
</head>
<body>
<input type="text" name="" id="input01"> <ul id="list01"></ul>
</body>
</html>
jsonp-360联想词获取示例
前端之json,ajax和jsonp的更多相关文章
- 前端跨域问题,以及ajax,jsonp,json的区别
看了很多网上的资料,小七感觉都没有完全解决我的疑惑以及问题,所以特意拿出通俗易懂的话讲解跨域问题,以及ajax,jsonp,json的区别.首先先说跨域问题什么时候需要跨域?[1]域名不同(即网址不同 ...
- json和jsonp的区别,ajax和jsonp的区别
json和jsonp虽然只有一个字母的区别,但是它们之间扯不上关系. json是一种轻量级的数据交换格式. jsonp是一种跨域数据交互协议. json的优点:(1)基于纯文本传递极其简单,(2)轻量 ...
- Jsonp 关键字详解及json和jsonp的区别,ajax和jsonp的区别
为什么要用jsonp? 相信大家对跨域一定不陌生,对同源策略也同样熟悉.什么,你没听过?没关系,既然是深入浅出,那就从头说起. 假如我写了个index页面,页面里有个请求,请求的是一个json数据(不 ...
- 前端学习——使用Ajax方式POST JSON数据包
0.前言 本文解释怎样使用Jquery中的ajax方法传递JSON数据包,传递的方法使用POST(当然PUT又有时也是一个不错的选择).POST JSON数据包相比标准的POST格式可读性更好 ...
- ajax使用json数组------前端往后台发送json数组及后台往前端发送json数组
1.引子 Json是跨语言数据交流的中间语言,它以键/值对的方式表示数据,这种简单明了的数据类型能被大部分编程语言理解.它也因此是前后端数据交流的主要方式和基础. 2.前端往后台传输json数据 第一 ...
- 原生 JavaScript 实现 AJAX、JSONP
相信大多数前端开发者在需要与后端进行数据交互时,为了方便快捷,都会选择JQuery中封装的AJAX方法,但是有些时候,我们只需要JQuery的AJAX请求方法,而其他的功能用到的很少,这显然是没必要的 ...
- jQuery ajax的jsonp跨域请求
一直在听“跨域跨域”,但是什么是跨域呢?今天做了一些了解.(利用jQuery的jsonp) jQuery使用JSONP跨域 JSONP跨域是利用script脚本允许引用不同域下的js实现的,将回调方法 ...
- 用原生JS实现AJAX和JSONP
前端开发在需要与后端进行数据交互时,为了方便快捷,都会选择JQuery中封装的AJAX方法,但是有些时候,我们只需要JQuery的AJAX请求方法,而其他的功能用到的很少,这显然是没必要的.其实,原生 ...
- ajax、反向ajax、jsonp详解
ajax详解 什么是ajax 其实ajax已经属于老技术了,现在几乎没人不会用了,在这里主要是把底层的东西给大家分享一下,以备应对装逼的面试官. ajax即“Asynchronous Javascri ...
随机推荐
- linux用户组相关,密码相关,文件操作,和启动级别
一.开机重启和用户切换 注意,当关机或重启前,都应当先执行一下sync指令,把内存的数据写入磁盘,防止数据丢失. shutdown命令 shutdown -h now :立即关机 shutdown - ...
- PC端视频播放器
视频播放器:Potplayer 它是一款纯净的.无广告.极速
- Win10 中 Git clone github上内容保存到指定文件夹
在要存储的右键→Git Bash Here 弹出命令窗口 输入 git clone 链接 很快就下载完成
- mybatis的mapper.xml中使用java类中的全局变量
select * from demo where status = '${@cn.jichi.Global@zz}'
- 一种简单实现Redis集群Pipeline功能的方法及性能测试
上一篇文章<redis pipeline批量处理提高性能>中我们讲到redis pipeline模式在批量数据处理上带来了很大的性能提升,我们先来回顾一下pipeline的原理,redis ...
- Java生鲜电商平台-缓存架构实战
Java生鲜电商平台-缓存架构实战 说明:在Java生鲜电商中,缓存起到了非常重要的作用,目前整个项目中才用的是redis做分布式缓存. 缓存集群 缓存集群存在的问题 1.热key 缓存集群中的某个k ...
- vscode解决nuget插件不能使用的问题
错误提示 使用vscode安装nuget插件之后出现错误: "Versioning information could not be retrieved from the NuGet pac ...
- vscode自动修复eslint规范的插件及配置
在开发大型项目中,经常都是需要多人合作的.相信大家一定都非常头疼于修改别人的代码的吧,而合理的使用eslint规范可以让我们在代码review时变得轻松,也可以让我们在修改小伙伴们的代码的时候会更加清 ...
- c程序内存检测工具 - Valgrind
常用C程序内存泄露检测工具 https://blog.csdn.net/u012662731/article/details/78652651
- Data Management Technology(4) -- 关系数据库理论
规范化问题的提出 在规范化理论出现以前,层次和网状数据库的设计只是遵循其模型本身固有的原则,而无具体的理论依据可言,因而带有盲目性,可能在以后的运行和使用中发生许多预想不到的问题. 在关系数据库系统中 ...