Last active
July 23, 2017 18:08
-
-
Save OlehRovenskyi/74deaabc9ea3e829e312e8900501fcb7 to your computer and use it in GitHub Desktop.
ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -------------- XMLHttpRequest -------------- | |
// 1. Создаём новый объект XMLHttpRequest | |
var xhr = new XMLHttpRequest(); | |
// 2. Конфигурируем его: GET-запрос на URL 'data.json' - синхронная обработка | |
xhr.open('GET', 'data.json', false); | |
// 3. Отсылаем запрос | |
xhr.send(); | |
// 4. Если код ответа сервера не 200, то это ошибка | |
if (xhr.status !== 200) { | |
// обработать ошибку | |
console.log( 'error', xhr.status + ': ' + xhr.statusText ); // пример вывода: 404: Not Found | |
} else { | |
// вывести результат | |
console.log( xhr.responseText ); // responseText -- текст ответа. | |
} | |
// ------------- function getJSON ------------- | |
function getJSON(url) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url); | |
xhr.onreadystatechange = function() { | |
if (this.readyState === 4 && this.status === 200) { | |
console.log(this.responseText); | |
console.log(typeof this.responseText); | |
console.log(JSON.parse(xhr.responseText)); | |
} | |
}; | |
xhr.send(); | |
} | |
// console.log('api', vote('', '/api/lessons/ajax/vote')); | |
console.log('basic getJSON', getJSON('data.json')); | |
// ------------- add handlers to getJSON function ------------- | |
function getJSON(url, successHandler, errorHandler) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url); | |
xhr.onreadystatechange = function() { | |
var status; | |
var data; | |
if (xhr.readyState === 4) { // `DONE` | |
status = xhr.status; | |
if (status === 200) { | |
data = JSON.parse(xhr.responseText); | |
successHandler && successHandler(data); | |
} else { | |
errorHandler && errorHandler(status); | |
} | |
} | |
}; | |
xhr.send(); | |
} | |
getJSON('data.json', function(data) { | |
console.log('Success ', data); | |
}, function(status) { | |
console.log('Something went wrong.', status); | |
}); | |
// ------------- add support old browsers ------------- | |
function getJSON(url, successHandler, errorHandler) { | |
var xhr = typeof XMLHttpRequest !== 'undefined' | |
? new XMLHttpRequest() | |
: new ActiveXObject('Microsoft.XMLHTTP'); | |
xhr.open('GET', url); | |
xhr.onreadystatechange = function() { | |
var status; | |
var data; | |
if (xhr.readyState === 4) { // `DONE` | |
status = xhr.status; | |
if (status === 200) { | |
data = JSON.parse(xhr.responseText); | |
successHandler && successHandler(data); | |
} else { | |
errorHandler && errorHandler(status); | |
} | |
} | |
}; | |
xhr.send(); | |
} | |
getJSON('data.json', function(data) { | |
console.log('Success ', data); | |
}, function(status) { | |
console.log('Something went wrong.', status); | |
}); | |
// ------------- xhr.responseType = 'json' ------------- | |
function getJSON(url, successHandler, errorHandler) { | |
var xhr = typeof XMLHttpRequest !== 'undefined' | |
? new XMLHttpRequest() | |
: new ActiveXObject('Microsoft.XMLHTTP'); | |
xhr.open('GET', url); | |
// browsers that support this feature automatically handle the JSON.parse() | |
xhr.responseType = 'json'; | |
xhr.onreadystatechange = function() { | |
var status; | |
var data; | |
if (xhr.readyState === 4) { // `DONE` | |
status = xhr.status; | |
if (status === 200) { | |
data = xhr.response; // JSON | |
successHandler && successHandler(data); | |
} else { | |
errorHandler && errorHandler(status); | |
} | |
} | |
}; | |
xhr.send(); | |
} | |
getJSON('data.json', function(data) { | |
console.log('Success ', data); | |
}, function(status) { | |
console.log('Something went wrong.', status); | |
}); | |
// ------------- support in IE ------------- | |
function getJSON(url, successHandler, errorHandler) { | |
var xhr = typeof XMLHttpRequest !== 'undefined' | |
? new XMLHttpRequest() | |
: new ActiveXObject('Microsoft.XMLHTTP'); | |
var responseType = 'responseType' in xhr; | |
// or | |
// browsers that support this feature automatically handle the JSON.parse() | |
// xhr.responseType = 'json'; | |
xhr.open('GET', url); | |
xhr.onreadystatechange = function() { | |
var status; | |
var data; | |
if (xhr.readyState === 4) { // `DONE` | |
status = xhr.status; | |
if (status === 200) { | |
data = responseType ? xhr.response : JSON.parse(xhr.responseText); | |
successHandler && successHandler(data); | |
} else { | |
errorHandler && errorHandler(status); | |
} | |
} | |
}; | |
xhr.send(); | |
} | |
getJSON('data.json', function(data) { | |
console.log('Success ', data); | |
}, function(status) { | |
console.log('Something went wrong.', status); | |
}); | |
// ------------- using with promises ------------- | |
var getJSON = function(url) { | |
return new Promise(function(resolve, reject) { | |
var xhr = new XMLHttpRequest(); | |
var responseType = 'responseType' in xhr; | |
xhr.open('get', url, true); | |
xhr.responseType = 'json'; | |
xhr.onload = function() { | |
var status = xhr.status; | |
var data; | |
if (status === 200) { | |
data = responseType ? xhr.response : JSON.parse(xhr.responseText); | |
resolve(data); | |
} else { | |
reject(status); | |
} | |
}; | |
xhr.send(); | |
}); | |
}; | |
getJSON('data.json').then(function(data) { | |
console.log('Success ', data); | |
}, function(status) { | |
console.log('Something went wrong.', status); | |
}); | |
// | |
var getFormData = function(el){ | |
var obj = {}; | |
var elements = el; | |
for( var i = 0; i < elements.length; ++i ) { | |
var element = elements[i]; | |
var name = element.name; | |
var value = element.value; | |
if( name ) { | |
obj[ name ] = value; | |
} | |
} | |
return obj; | |
}; | |
var form = document.forms.user; | |
form.addEventListener('submit', function(e) { | |
e.preventDefault(); | |
var formObj = getFormData(form); | |
var formData = ''; | |
for (var key in formObj) { | |
formData += key + '=' + formObj[key] + '&'; | |
} | |
// sent to server | |
// var xhr = new XMLHttpRequest(); | |
// | |
// xhr.open("POST", '/url'); | |
// xhr.send(formData); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment