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使用方法
常用参数:

  1. url 请求地址
  2. type 请求方式,默认是'GET',常用的还有'POST'
  3. dataType 设置返回的数据格式,常用的是'json'格式,也可以设置为'html'
  4. data 设置发送给服务器的数据
  5. success 设置请求成功后的回调函数
  6. error 设置请求失败后的回调函数
  7. 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的更多相关文章

  1. 前端跨域问题,以及ajax,jsonp,json的区别

    看了很多网上的资料,小七感觉都没有完全解决我的疑惑以及问题,所以特意拿出通俗易懂的话讲解跨域问题,以及ajax,jsonp,json的区别.首先先说跨域问题什么时候需要跨域?[1]域名不同(即网址不同 ...

  2. json和jsonp的区别,ajax和jsonp的区别

    json和jsonp虽然只有一个字母的区别,但是它们之间扯不上关系. json是一种轻量级的数据交换格式. jsonp是一种跨域数据交互协议. json的优点:(1)基于纯文本传递极其简单,(2)轻量 ...

  3. Jsonp 关键字详解及json和jsonp的区别,ajax和jsonp的区别

    为什么要用jsonp? 相信大家对跨域一定不陌生,对同源策略也同样熟悉.什么,你没听过?没关系,既然是深入浅出,那就从头说起. 假如我写了个index页面,页面里有个请求,请求的是一个json数据(不 ...

  4. 前端学习——使用Ajax方式POST JSON数据包

    0.前言     本文解释怎样使用Jquery中的ajax方法传递JSON数据包,传递的方法使用POST(当然PUT又有时也是一个不错的选择).POST JSON数据包相比标准的POST格式可读性更好 ...

  5. ajax使用json数组------前端往后台发送json数组及后台往前端发送json数组

    1.引子 Json是跨语言数据交流的中间语言,它以键/值对的方式表示数据,这种简单明了的数据类型能被大部分编程语言理解.它也因此是前后端数据交流的主要方式和基础. 2.前端往后台传输json数据 第一 ...

  6. 原生 JavaScript 实现 AJAX、JSONP

    相信大多数前端开发者在需要与后端进行数据交互时,为了方便快捷,都会选择JQuery中封装的AJAX方法,但是有些时候,我们只需要JQuery的AJAX请求方法,而其他的功能用到的很少,这显然是没必要的 ...

  7. jQuery ajax的jsonp跨域请求

    一直在听“跨域跨域”,但是什么是跨域呢?今天做了一些了解.(利用jQuery的jsonp) jQuery使用JSONP跨域 JSONP跨域是利用script脚本允许引用不同域下的js实现的,将回调方法 ...

  8. 用原生JS实现AJAX和JSONP

    前端开发在需要与后端进行数据交互时,为了方便快捷,都会选择JQuery中封装的AJAX方法,但是有些时候,我们只需要JQuery的AJAX请求方法,而其他的功能用到的很少,这显然是没必要的.其实,原生 ...

  9. ajax、反向ajax、jsonp详解

    ajax详解 什么是ajax 其实ajax已经属于老技术了,现在几乎没人不会用了,在这里主要是把底层的东西给大家分享一下,以备应对装逼的面试官. ajax即“Asynchronous Javascri ...

随机推荐

  1. QT QSplitter设置初始比例setStretchFactor失效解决

    QSplitter如下为常用 设置显示比例 pRightSplitter=new QSplitter(Qt::Vertical); pRightSplitter->setMouseTrackin ...

  2. STM32F429的新版用户手册更新记录, 改进、交流(2019-08-18发布V0.9版本)

    2019-06-16 发布首版V0.1 2019-06-23 发布V0.2版本 新增章节: 第3章 STM32F429 整体把控 第4章 STM32F429 工程模板建立(MDK5) 第5章 STM3 ...

  3. 编码方式ASCII、GBK、Unicode、UTF-8比较

    文章内容深度较浅,详细了解可到下链接:https://blog.csdn.net/QuinnNorris/article/details/78705723; 总结了以下几种编码方式: ASCII.GB ...

  4. Java变量在内存中的存储

    目录 Java变量在内存中的存储 成员变量 局部变量 总结 Java变量在内存中的存储 以下探究成员变量和局部变量在内存中的存储情况. package com.my.pac04; /** * @aut ...

  5. WebShell代码分析溯源(二)

    WebShell代码分析溯源(二) 一.一句话变形马样本 <?php $POST['POST']='assert';$array[]=$POST;$array[0]['POST']($_POST ...

  6. docker采用Dockerfile安装jdk1.8案例

    1 获取一个简单的Docker系统镜像,并建立一个容器. 这里我选择下载CentOS镜像 docker pull centos 通过docker tag命令将下载的CentOS镜像名称换成centos ...

  7. swool安装(centos7)

    1:获取swoole https://github.com/swoole/swoole-src/releases http://pecl.php.net/package/swoole http://g ...

  8. SpringBoot+MyBatisPlus整合时提示:Invalid bound statement(not found):**.dao.UserDao.queryById

    场景 在使用SpringBoot+MyBatisPlus搭建后台启动项目时,使用EasyCode自动生成代码. 在访问后台接口时提示: Invilid bound statement (not fou ...

  9. Prism_Commanding(2)

    Commanding 除了提供对要在视图中显示或编辑的数据的访问之外,ViewModel还可能定义可由用户执行的一个或多个动作或操作.用户可以通过UI执行的动作或操作通常被定义为命令.命令提供了一种方 ...

  10. 【转】Kotlin的inline内联函数

    原文链接:https://blog.csdn.net/Jaden_hool/article/details/78437947 方法调用流程 调用一个方法是一个压栈和出栈的过程,调用方法时将栈针压入方法 ...