or...in语句解析
<script>
var json={a: 12, b: 5};
for(var i in json)
{
alert(i+'='+json[i]);
}
</script>
eval() 函数可计算某个字符串, 并执行其中的的 JavaScript 代码。
服务器端脚本代码:
<?php
$row=array('username'=>'lisi','password'=>'222222');
echo json_encode($row);
/*$data=array(
array('name'=>'zhangsan','age'=>18),
array('name'=>'lisi','age'=>30)
);
echo json_encode($data);
*/
?>
var json=eval('('+value+')'); 主要是针对关联数组
返回:"{name:'zhangsan',age:18}"
访问方式:json.username+json.password
var json=eval(value); 主要是针对索引数组
返回:"[{name:'zhangsan',age:18},{name:'lisi',age:20}]"
访问方式:json[0].name+json[0].age
注意:索引数组的解析也可以采用 var json=eval(value);
<script language="javascript" src="public.js"></script>
<script>
var xhr=createxhr(); //创建ajax对象, 代码见ajax | ajax封装GET和POST
xhr.open('post','demo05.php');
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
var value=xhr.responseText; //返回的是字符串
//1)
var json=eval('('+value+')'); //返回是json对象
alert(json.username+json.password);
//2)
//var json=eval(value); //返回是json数组对象
//alert(json[1].name+json[1].age);
}
};
xhr.send(null);
</script>
返回:"{name:’zhangsan’,age:18}"
解析格式:eval('('+value+')');
返回:"[{name:'zhangsan',age:18},{name:'lisi',age:20}]"
解析格式:eval(value);
也可以采用eval('('+value+')');
实例1:
<html>
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript">
function f1(){
//ajax去服务器获得json信息
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
//alert(xhr.responseText);//字符串{"north":"wolf","helan":"pig","germany":"dog"}
var info = eval('('+xhr.responseText+')');
//也可写成:eval("var info="+xhr.responseText);
document.write(info.north);
document.write(info.helan);
document.write(info.germany);
}
}
xhr.open('get','03.php');
xhr.send(null);
}
//javascript把一个字符串变为对象
//var a = '{"north":"wolf","helan":"pig","germany":"dog"}';
//eval(参数字符串)
//eval("var obj="+a);//eval('var obj={"north":"wolf","helan":"pig","germany":"dog"}');
//document.write(obj);//访问对象
</script>
</head>
<body>
<h2>静态网站,javascript对json的接收处理</h2>
<input type="button" value="触发" onclick="f1()" />
</body>
</html>
<?php
//对外提供json信息
header("Cache-Control:no-cache,must-revalidate");
$animal = array('north'=>'wolf','helan'=>'pig','germany'=>'dog');
echo json_encode($animal); //{"north":"wolf","helan":"pig","germany":"dog"}
?>
在javascript解析{"north":"wolf","helan":"pig","germany":"dog"}
采用:var info = eval('('+xhr.responseText+')'); 语法
也可写成:eval("var info="+xhr.responseText);
实例2:
<html>
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript">
function f1(){
//ajax去服务器获得json信息
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
//alert(xhr.responseText);//数组 ["wolf","pig","dog"]
var info = eval(xhr.responseText);
document.write(info[0]+info[1]+info[2]);
}
}
xhr.open('get','03.php');
xhr.send(null);
}
</script>
</head>
<body>
<h2>静态网站,javascript对json的接收处理</h2>
<input type="button" value="触发" onclick="f1()" />
</body>
</html>
<?php
//对外提供json信息
header("Cache-Control:no-cache,must-revalidate");
$animal = array('wolf','pig','dog');
echo json_encode($animal); //["wolf","pig","dog"]
?>
在javascript解析["wolf","pig","dog"]时
采用:var info = eval(xhr.responseText);语法
实例3:
<html>
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript">
function f1(){
//ajax去服务器获得json信息
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
var s = "";
//alert(xhr.responseText);//数组对象[{"id":1,"name":"xutao","sex":"\u7537","age":30},...]
var info = eval(xhr.responseText);
for(var i=0;i<info.length;i++){
s += info[i].id + "--" + info[i].name + "--" + info[i].sex + "--" + info[i].age +"<br />";
}
document.getElementById("user").innerHTML = s;
}
}
xhr.open('get','info.php');
xhr.send(null);
}
</script>
</head>
<body>
<h2>静态网站,javascript对json的接收处理</h2>
<input type="button" value="触发" onclick="f1()" />
<div id="user"></div>
</body>
</html>
<?php
$info = array(
array("id"=>1,"name"=>"zhangsan","sex"=>"男","age"=>30),
array("id"=>2,"name"=>"lisi","sex"=>"女","age"=>27),
array("id"=>3,"name"=>"wangwu","sex"=>"男","age"=>6)
);
echo json_encode($info);
/* [{"id":1,"name":"zhangsan","sex":"\u7537","age":30},
{"id":2,"name":"lisi","sex":"\u5973","age":27},
{"id":3,"name":"wuwang","sex":"\u7537","age":6}] */
?>
在javascript解析[{"id":1,"name":"zhangsan","sex":"\u7537","age":30},
{"id":2,"name":"lisi","sex":"\u5973","age":27},
{"id":3,"name":"wuwang","sex":"\u7537","age":6}]时
采用:var info = eval(xhr.responseText);语法
从数据库读取出来的二维数组,通过json_encode()编码后, 在javascript进行解析时也是采用上述语法。
ebpack除了可以处理加载页面资源文件引用之外,还可以加载的资源有数据文件,如 JSON 、CSV、TSV 和 XML格式的文件。类似于 NodeJS, 内置的支持JSON格式的数据,其可以通过 import Data from './data.json' 引入并正常运行。但是要导入 CSV、TSV 和 XML格式的文件,需要使用 对应的csv-loader 和 xml-loader的loader,来处理加载这三类文件。
创建一个工程名为:webpack-datafile,并进行相应内容的初始化。
mkdir webpack-datafile
cd webpack-datafile
npm init -y
npm install webpack webpack-cli --save-dev
工程目录结构如下:
工程目录结构
手下在src目录下添加数据资源文件data.xml,data.csv。
其中data.xml文件的内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<email>
<from>张三</from>
<to>李四</to>
<subjet>会议</subjet>
<body>明天上午8点,会议室开会!</body>
</email>
data.csv的内容
from,to,subject,body
张三,李四,会议,明天上午8点开会
李四,王五,采购,明天采购一台笔记本
然后在src/index.js中,引入数据文件,并进行数据的读取操作。
import email from './data.xml'
import emails from './data.csv'
console.log(email)
console.log(emails)
执行在本地安装 数据解析loader:csv-loader 和 xml-loader
npm install csv-loader xml-loader --save-dev
完善webpack的配置文件,使其进行项目构建时可以解析xml、csv格式的文件:
const path=require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname,'dist')
},
module: {
rules: [
{
test: /\.xml$/i,
use: ['xml-loader']
},
{
test: /\.csv$/i,
use: ['csv-loader']
}
]
}
}
然后执行npm run build进行项目的构建。
npm run build
> webpack-datafile@1.0.0 build D:\work\webpack5\webpack-datafile
> webpack
asset bundle.js 753 bytes [emitted] [minimized] (name: main)
runtime modules 663 bytes 3 modules
cacheable modules 399 bytes
./src/index.js 106 bytes [built] [code generated]
./src/data.xml 131 bytes [built] [code generated]
./src/data.csv 162 bytes [built] [code generated]
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
webpack 5.28.0 compiled with 1 warning in 579 ms
进入构建之后的目录并打开index.html,查看控制台输出的数据内容:
效果
可以看到,控制台输出一个对象和一个数组。
小节基本要求
要点:
利用Ajax动态获取文章数据,成就动态页面。
新建文件夹,建立一个.json后缀的文件,这个文件里存放的是我们的文章数据。
代码如下:
{
"hot": [
{ "id": 1,
"title": "Zabbix"
},
{
"id": 2,
"title": "Prometheus"
},
{
"id": 3,
"title": "Java yyds!"
},
{
"id": 4,
"title": "什么?卡卡罗特对波又输了?"
},
{
"id": 5,
"title": "一千零一夜"
},
{
"id": 100,
"title": "问风"
}
],
"new": [
{ "id": 6,
"title": "ElasticSearch"
},
{
"id": 7,
"title": "Kafka"
},
{
"id": 8,
"title": "从你的全世界路过"
},
{
"id": 9,
"title": "如果那天可以好好聊聊"
},
{
"id": 10,
"title": "带着记忆回到14年"
},
{
"id": 11,
"title": "孤流拒海"
}
]
}
什么?你问我JSON格式的数据为什么长这样?为什么带个{},为什么带个[ ]?
因为大家都这样写,所有就成这样咯。
ps:现在开发网站几乎全部都是用的json格式构建的数据。学会这种格式,难道不重要吗?
这是一个很火的学习网站:www.baidu.com
这点作了修改,给ul添加了Id选择器。
为什么添加ID选择器,看Step4
下载地址:https://code.jquery.com/jquery-1.11.0.min.js
直接右键屏幕另存为就可以了。
创建js文件夹,将文件放入,并且在body.html页面引入该文件:如下:
<script src="../js/jquery-3.1.1.js"></script>
代码如下:
<script type="text/javascript">
function getData() {
$.ajax({
type: "GET",
url: "../data/article.json",
dataType: "json",
headers:{'Content-Type':'application/json;charset=utf8'},
success: function (res) {
let hot_w = res.hot;
let new_w = res.new;
var hot_html = ""
var new_html = ""
hot_w.forEach(function (d) {
var h = "<li>" + d.title + "</li>"
hot_html += h;
})
new_w.forEach(function (d) {
var n = "<li>" + d.title + "</li>"
new_html += n;
})
console.log($.parseHTML(hot_html))
console.log($(".hot .card-body ul"))
$("#hot-w").append($.parseHTML(hot_html))
$("#new-w").append($.parseHTML(new_html))
}
})
}
getData()
</script>
附本篇body.html中的所有追加的代码:
JS部分:
<script src="../js/jquery-3.1.1.js"></script>
<script type="text/javascript">
function getData() {
$.ajax({
type: "GET",
url: "../data/article.json",
dataType: "json",
headers:{'Content-Type':'application/json;charset=utf8'},
success: function (res) {
let hot_w = res.hot;
let new_w = res.new;
var hot_html = ""
var new_html = ""
hot_w.forEach(function (d) {
var h = "<li>" + d.title + "</li>"
hot_html += h;
})
new_w.forEach(function (d) {
var n = "<li>" + d.title + "</li>"
new_html += n;
})
console.log($.parseHTML(hot_html))
console.log($(".hot .card-body ul"))
$("#hot-w").append($.parseHTML(hot_html))
$("#new-w").append($.parseHTML(new_html))
}
})
}
getData()
</script>
<body>
<div class="tbody">
<main class="is-main">
<div class="main-left">
<div class="gonggao">
哈喽,我是公告位
</div>
<div class="panel">
<div class="guangao">哈喽,我是广告位</div>
</div>
<div class="content">
<div class="card">
<div class="hot">
我是热门文章
</div>
<div class="card-body">
<ul id="hot-w">
</ul>
</div>
</div>
<div class="card">
<div class="new">
我是最新文章
</div>
<div class="card-body">
<ul id="new-w">
</ul>
</div>
</div>
</div>
</div>
<div class="main-right">
<!-- <div class="my-info">-->
<!-- 我是个人信息框-->
<!-- </div>-->
</div>
</main>
</div>
</body>
一种用于请求网址的技术
一种脚本语言,你所看到的所有网站都离不开这门技术
样式选择器,前几篇讲过类选择器,详细了解入口,www.baidu.com
你所看到的所有网站的数据目前几乎都是以JSON格式交互的
*请认真填写需求信息,我们会在24小时内与您取得联系。