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小時內與您取得聯系。