JS之 Ajax 组件和库
Posted 架构师日刊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS之 Ajax 组件和库相关的知识,希望对你有一定的参考价值。
大家好,我是你们的导师,我每天都会在这里给大家分享一些干货内容(当然了,周末也要允许老师休息一下哈)。上次老师跟大家分享了JS 之 继承关系的知识,今天跟大家分享下JS之 Ajax 组件和库的知识。
fetch('https://www.example.com', {
method: 'get'
})
.then(response => response.json())
.then(jsonData => console.log(jsonData))
.catch(err => {
//error block
})
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'blizzerand')
fetch('/avatars', {
method: 'POST',
body: data
})
npm install axios
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
var data = new FormData();
data.append('foo', 'bar');
data.append('file', document.getElementById('file').files[0]);
var config = {
onUploadProgress: function(progressEvent) {
var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
}
};
axios.put('/upload/server', data, config)
.then(function (res) {
output.className = 'container';
output.innerhtml = res.data;
})
.catch(function (err) {
output.className = 'container text-danger';
output.innerHTML = err.message;
});
$.ajax({
url: '/users',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
}
fail: function () {
console.log("Encountered an error")
}
});
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.then(function(res) {
alert('yay got ' + JSON.stringify(res.body));
});
request
.post('/upload')
.field('user[name]', 'Tobi')
.field('user[email]', 'tobi@learnboost.com')
.field('friends[]', ['loki', 'jane'])
.attach('image', 'path/to/tobi.png')
.then(callback);
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
参考文献:http://www.codeceo.com/article/5-javascript-ajax-libs.html
以上是关于JS之 Ajax 组件和库的主要内容,如果未能解决你的问题,请参考以下文章