javascript XMLHttpRequest RESTful(GET,POST,PUT,DELETE)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript XMLHttpRequest RESTful(GET,POST,PUT,DELETE)相关的知识,希望对你有一定的参考价值。
// Get all users
var url = "http://localhost:8080/api/v1/users";
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
// Get a user
var url = "http://localhost:8080/api/v1/users";
var xhr = new XMLHttpRequest()
xhr.open('GET', url+'/1', true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
// Post a user
var url = "http://localhost:8080/api/v1/users";
var data = {};
data.firstname = "John";
data.lastname = "Snow";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
// Update a user
var url = "http://localhost:8080/api/v1/users";
var data = {};
data.firstname = "John2";
data.lastname = "Snow2";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("PUT", url+'/12', true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
// Delete a user
var url = "http://localhost:8080/api/v1/users";
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url+'/12', true);
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
以上是关于javascript XMLHttpRequest RESTful(GET,POST,PUT,DELETE)的主要内容,如果未能解决你的问题,请参考以下文章
执行用包含脚本标签的 XMLHttpRequest 编写的 Javascript?
运行使用 XMLHttpRequest 下载的 JavaScript
JavaScript中的XMLHttpRequest与WebAPI
JavaScript(Navigator/Screen/Cookie/XMLHttpRequest/CORS)
如何处理 XMLHttpRequest 下载文件中的 javascript? [复制]
如何在 JavaScript 中使用 XMLHttpRequest 设置 Cookie(标头)?