OK
Now we are going to learn Web Development.
API
Application Programming Interface
An API specifies some form of software or hardware interation, in terms of
1.Inputs
2.Processes
3.Outputs
REST
Representational State Transfer Achitecture
API is RESTful if it meets several architectural constraints
GET
PUT
POST
DELETE
Data
usually JSON
sometimes XML or other formats
How do we read or interact with data?
JavaScript--use it like an Object
Python/other languages--use a library
现在我们来试一下用js的XMLHttpRequest
我们借用一下https://sunrise-sunset.org/api 这个网站的api
这是可以用的api
https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400
https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=today
https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2019-11-20
https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&formatted=0
地址是
https://api.sunrise-sunset.org/json
然后在后面加上参数
比如第一个就是
https://api.sunrise-sunset.org/json 再加lat=36.72... lng=-4.42.....
所以我们可以给这个api发送请求
然后加上自定义的lat和lng
代码
<script>
var processResponse = function () {
console.log(this);
}
var url = 'https://api.sunrise-sunset.org/json';
var lat = 1.0;
var lng = 1.0;
var query_url = url + "?lat=" + lat + "&lng=" + lng;
var xhttp = new XMLHttpRequest();
xhttp.addEventListener('load', processResponse);
xhttp.open('GET', query_url);
xhttp.send();
</script>
发送请求,看一下console
看一下response
response: "{"results":{"sunrise":"5:39:28 AM","sunset":"5:43:51 PM","solar_noon":"11:41:40 AM","day_length":"12:04:23","civil_twilight_begin":"5:17:35 AM","civil_twilight_end":"6:05:44 PM","nautical_twilight_begin":"4:52:04 AM","nautical_twilight_end":"6:31:15 PM","astronomical_twilight_begin":"4:26:29 AM","astronomical_twilight_end":"6:56:51 PM"},"status":"OK"}"
responseText: "{"results":{"sunrise":"5:39:28 AM","sunset":"5:43:51 PM","solar_noon":"11:41:40 AM","day_length":"12:04:23","civil_twilight_begin":"5:17:35 AM","civil_twilight_end":"6:05:44 PM","nautical_twilight_begin":"4:52:04 AM","nautical_twilight_end":"6:31:15 PM","astronomical_twilight_begin":"4:26:29 AM","astronomical_twilight_end":"6:56:51 PM"},"status":"OK"}"
responseType: ""
我们用json.cn来把json格式化一下,比较好看一点
{
"results":{
"sunrise":"5:39:28 AM",
"sunset":"5:43:51 PM",
"solar_noon":"11:41:40 AM",
"day_length":"12:04:23",
"civil_twilight_begin":"5:17:35 AM",
"civil_twilight_end":"6:05:44 PM",
"nautical_twilight_begin":"4:52:04 AM",
"nautical_twilight_end":"6:31:15 PM",
"astronomical_twilight_begin":"4:26:29 AM",
"astronomical_twilight_end":"6:56:51 PM"
},
"status":"OK"
}
{
"results":{
"sunrise":"5:39:28 AM",
"sunset":"5:43:51 PM",
"solar_noon":"11:41:40 AM",
"day_length":"12:04:23",
"civil_twilight_begin":"5:17:35 AM",
"civil_twilight_end":"6:05:44 PM",
"nautical_twilight_begin":"4:52:04 AM",
"nautical_twilight_end":"6:31:15 PM",
"astronomical_twilight_begin":"4:26:29 AM",
"astronomical_twilight_end":"6:56:51 PM"
},
"status":"OK"
}
然后我们可以用js来解析一下JSON
代码
<script>
var processResponse = function () {
console.log(this);
var res = this.response;
console.log(res);
var data = JSON.parse(res);
console.log(data);
var results = data.results;
console.log(results);
var sunrise = results.sunrise;
console.log(sunrise);
var sunset = results.sunset;
console.log(sunset);
}
var url = 'https://api.sunrise-sunset.org/json';
var lat = 1.0;
var lng = 1.0;
var query_url = url + "?lat=" + lat + "&lng=" + lng;
var xhttp = new XMLHttpRequest();
xhttp.addEventListener('load', processResponse);
xhttp.open('GET', query_url);
xhttp.send();
</script>
现在js已经用fetch取代了XMLHttpRequest处理异步请求
所以我们用fetch来试试
代码
<script>
// var processResponse = function () {
// console.log(this);
//
// var res = this.response;
// console.log(res);
//
// var data = JSON.parse(res);
// console.log(data);
//
// var results = data.results;
// console.log(results);
//
// var sunrise = results.sunrise;
// console.log(sunrise);
//
// var sunset = results.sunset;
// console.log(sunset);
// }
var url = 'https://api.sunrise-sunset.org/json';
var lat = 1.0;
var lng = 1.0;
var query_url = url + "?lat=" + lat + "&lng=" + lng;
// var xhttp = new XMLHttpRequest();
// xhttp.addEventListener('load', processResponse);
// xhttp.open('GET', query_url);
// xhttp.send();
fetch(query_url)
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
</script>
fetch是原生js,但是有各种问题
axios是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范
又没用fetch的各种问题
我们来试试axios
<script>
// var processResponse = function () {
// console.log(this);
//
// var res = this.response;
// console.log(res);
//
// var data = JSON.parse(res);
// console.log(data);
//
// var results = data.results;
// console.log(results);
//
// var sunrise = results.sunrise;
// console.log(sunrise);
//
// var sunset = results.sunset;
// console.log(sunset);
// }
var url = 'https://api.sunrise-sunset.org/json';
var lat = 1.0;
var lng = 1.0;
var query_url = url + "?lat=" + lat + "&lng=" + lng;
// var xhttp = new XMLHttpRequest();
// xhttp.addEventListener('load', processResponse);
// xhttp.open('GET', query_url);
// xhttp.send();
// fetch(query_url)
// .then(function (response) {
// return response.json();
// })
// .then(function (data) {
// console.log(data);
// })
axios.get(query_url)
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
</script>
========
1.) Hello
- file:
hello.js
- test:
test/test_hello.js
This function accepts a String as input and should return that String with hello
prepended to it.
2.) Sumall
- file:
sumall.js
- test:
test/test_sumall.js
This function accepts a number as input. It then returns the sum of all numbers lower than or equal to this value. For example, if given the input 5
, it should return 15
- (5 + 4 + 3 + 2 + 1
)
3.) Sumall35
- file:
sumall35.js
- test:
test/test_sumall35.js
This function accepts a number as input. It then returns the sum of all numbers lower than this value that are exactly divisible by 3 or 5. For example, if given the input 7
, it should return 14
- (6 + 5 + 3
)
4.) Largest
- file:
largest.js
- test:
test/test_largest.js
This accepts an Array as input and should return the largest value in the Array. For example, if given the input [4, 3, 2]
it should return 4
5.) HighestLowest
- file:
highestlowest.js
- test:
test/test_highestlowest.js
This function accepts a String as input. This String will be a set of space separated numbers. The function should return the highest and lowest numbers in the String, as another space separated String, with the highest number first. For example, given the input "4 6 8"
it should return "8 4"
6.) Even Or Odd
- file:
evenorodd.js
- test:
test/test_even_or_odd.js
This function takes a number as input and returns “even” if the number is even (exactly divisible by 2) or “odd” if the number is odd.
7.) MakeNegative
- file:
makenegative.js
- test:
test/test_makenegative.js
This function takes a number as input. If the number is positive, it returns a negative number with the same magnitude. If the number is negative, it returns the number. So, for example, given the input 5
it should return -5
8.) Middle
- file:
middle.js
- test:
test/test_middle.js
This function takes a String as input. If the length of the String is odd, it returns the middle character of the String. If the length of the String is even, it returns the middle two characters.
9.) Mumbling
- file:
mumbling.js
- test:
test/test_mumbling.js
This function accepts a String as input and returns a new String made up of the characters of the original string repeated n
times, where n
is their position in the original String. The set of repeated characters should be in TitleCase. For example, given the input her
it should return H-Ee-Rrr
10.) Palindrome
- file:
palindrome.js
- test:
test/test_palindrome.js
This function returns true
if the supplied input String is a palindrome, false
if not. A palindrome is a word that is spelt the same backwards and forwards.
11.) Repeat String
- file:
repeatstring.js
- test:
test/test_repeatstring.js
This function accepts a String s
as input and a number n
and returns the String s
repeated n
times. For example, if given the input hi
and 6, it would return hihihihihihi
12.) Smush
- file:
smush.js
- test:
test/test_smush.js
This function accepts two Arrays as inputs, and returns a new array formed by stitching the two Arrays together an element at a time. For example, given the input [5, d]
and [f, 6]
it should return [5, f, d, 6]
13.) Population
- file:
population.js
- test:
test/test_population.js
This function models population growth to see how long it will take a town of a certain size to reach a target population. It has a number of parameters:
- the starting population
- the natural percentage increase each year
- the number of people who move to the town each year
- the target population
The function will use the first three parameters to calculate and return the number of years before the population hits the supplied target.
做一下练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function hello(str) {
return str + 'hello';
}
function sumall(num) {
var sum = 0;
for (let i = 1; i <= num; i++) {
sum = sum + i;
}
return sum;
}
function sumall35() {
var sum = 0;
for (let i = 1; i <= num; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum = sum + i;
}
}
return sum;
}
function largest(list) {
var max = list[0];
for (let i = 0; i < list.length; i++) {
if (list[i] >= max) {
max = list[i]
}
}
return max
}
function lowest(list) {
var min = list[0];
for (let i = 0; i < list.length; i++) {
if (list[i] <= min) {
min = list[i]
}
}
return min
}
function HighestLowest(str) {
list = str.split(' ');
var max = largest(list);
var min = lowest(list);
return "" + max + " " + min
}
function EvenOrOdd(num) {
if (num % 2 == 0) {
return 'even'
} else {
return 'odd'
}
}
function MakeNegative(num) {
if (num > 0) {
return -num;
} else {
return num;
}
}
function Middle(str) {
let list = str.split('');
let len = list.length
if (len % 2 == 0) {
return list[(len - 1) / 2] + list[len / 2]
} else {
return list[len / 2]
}
}
function Mumbling(str) {
let list = str.split('');
let result = '';
for (let i = 0; i < list.length; i++) {
for (let j = 1; j < i; j++) {
if (j == 1) {
result = result + list[i].toUpperCase();
} else {
result = result + list[i].toLowerCase();
}
}
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge"/>
<title>JavaScript, Events and DOM</title>
</head>
<body>
<p>Hello <span id="name-output"></span></p>
<form>
<label for="name-input">Enter your name:</label>
<input type="text" name="" id="name-input"/>
<input type="button" value="Submit" id="submit-button"/>
</form>
<script type="text/javascript">
function sayHello(name) {
let textSpan = document.getElementById("name-output");
textSpan.innerHTML = "";
let nameText = document.createTextNode(name);
textSpan.appendChild(nameText);
}
let submitButton = document.getElementById("submit-button");
console.log(submitButton);
submitButton.addEventListener("click", function () {
let nameInput = document.getElementById("name-input");
sayHello(nameInput.value);
});
</script>
</body>
</html>