Skip to content

Instantly share code, notes, and snippets.

@liuxiaomingskm
Last active February 2, 2020 17:38
Show Gist options
  • Save liuxiaomingskm/05359f30569647955f40bab7e7b7d932 to your computer and use it in GitHub Desktop.
Save liuxiaomingskm/05359f30569647955f40bab7e7b7d932 to your computer and use it in GitHub Desktop.
AJAX 4 Ways Exercise (用XML,fetch,JQuery, Axios四种方式调用api并显示)
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src=" https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<h1>Ron Swanson Quote Generator</h1>
<p>(4 ways of writing AJAX requests)</p>
<section class="container">
<button id="xhr">XHR</button>
<button id="fetch">Fetch</button>
<button id="jquery">jQuery</button>
<button id="axios">Axios</button>
</section>
<p id="quote">Quote Goes Here...</p>
var url = 'https://ron-swanson-quotes.herokuapp.com/v2/quotes';
var xhrbtn = document.querySelector("#xhr");
var fetchbtn = document.querySelector("#fetch");
var jquerybtn = document.querySelector("#jquery");
var axiosbtn = document.querySelector("#axios");
var display = document.querySelector("#quote");
//XHR section
xhrbtn.addEventListener("click",function(){
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function(){
if (XHR.readyState == 4 && XHR.status == 200){
var quote = JSON.parse(XHR.responseText)[0];
console.log(quote);
display.innerHTML = quote;
}
}
XHR.open("GET", url);
XHR.send();
});
//fectch section
fetchbtn.addEventListener("click",function(){
fetch(url)
.then(function(req){
req.json().then(function(data){
display.innerHTML = data[0];
})
})
.catch(function(){
})
});
//JQuery section
$("#jquery").click(function(){
$.getJSON(url)
.done(function(data){
$("#quote").text(data[0]);
})
});
//Axios section
axiosbtn.addEventListener("click",function(){
axios.get(url)
.then(function(res){
display.innerHTML = res.data[0];
})
.catch(function(){
alert("Error!");
})
});
@import url('https://fonts.googleapis.com/css?family=Roboto');
body {
font-family: 'Roboto';
color: #2c3e50;
text-align: center;
}
#quote {
font-size: 20px;
}
.container {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
button {
margin-top: 20px;
background: red;
border: none;
outline: none;
height: 40px;
text-align: center;
width: 130px;
border-radius: 40px;
background: #fff;
border: 2px solid #1abc9c;
color: #1abc9c;
letter-spacing: 1px;
text-shadow: 0;
font-size: 12px;
font-weight: bold;
cursor: pointer;
-webkit-transition: all 0.25s ease;
transition: all 0.25s ease;
font-family: 'Roboto', sans-serif;
}
button:hover {
color: white;
background: #1abc9c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment