如何使用HTTP GET或POST进行Ajax调用
我们需要使用JavaScript和一个像jQuery、Axios或Fetch API这样的AJAX库来使用HTTP GET或POST进行AJAX调用。Ajax(异步JavaScript和XML)通过异步更新内容而无需重新加载整个页面来创建快速和动态的网页。它使用JavaScript从服务器发送和接收数据,可以是XML、JSON或纯文本。本教程将教我们如何使用HTTP GET或POST进行Ajax调用。
Ajax有两种常见的请求类型:GET和POST。
GET请求
GET请求用于从服务器检索数据。GET请求通常用于从API检索数据,因为它们不对服务器进行任何更改,因此被视为安全和幂等。
语法
用户可以按照以下语法使用GET请求进行Ajax调用使用JavaScript的‘ XMLHttpRequest ’对象。
let xhr = new XMLHttpRequest();
xhr.open("GET", "URL", true);
xhr.send();
这将创建一个新的’XMLHttpRequest’对象,并打开一个GET请求到给定的URL。最后,xhr.send( )方法被用来将GET请求发送到服务器。
请注意,您将需要提供您想要检索数据的API URL。
示例
下面的示例演示了如何在JavaScript中进行一个GET请求,以从 https://jsonplaceholder.typicode.com/posts API获取数据。代码使用XMLHttpRequest对象打开一个GET请求,并处理来自服务器的响应。响应数据被解析为JSON对象,并使用innerHTML属性在页面上显示前3个帖子的标题。
JSONPlaceholder API是一个用于测试和原型设计的免费和开源的API。您也可以使用任何其他API。
<html>
<body>
<h2><i>GET</i> Method Example</h2>
<h3>Top 3 Blog Posts:</h3>
<div id = "posts"> </div>
<script>
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
let output = "";
for (let i = 0; i < 3; i++) {
output += "<p>" + data[i].title + "</p>";
}
document.getElementById("posts").innerHTML = output;
}
};
xhr.send();
</script>
</body>
</html>
使用XMLHttpRequest对象进行POST请求
XMLHttpRequest可以用来进行POST请求,类似于GET请求,但数据是通过请求体而不是URL发送的。open方法用于设置请求方法为”POST”和URL,send方法用于发送数据,onreadystatechange事件用于处理服务器返回的响应。还可以根据需要设置内容类型和其他头部信息。
语法
用户可以按照下面的语法来使用POST请求进行Ajax调用。
var xhr = new XMLHttpRequest();
xhr.open("POST", "URL", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(postData));
示例
下面的示例演示了使用XMLHttpRequest对象进行POST请求。我们创建了一个表单,其中包含两个输入字段用于输入文章标题和正文,以及一个提交按钮。当点击提交按钮时,将调用sendPostRequest()函数,该函数创建一个POST请求到”https://jsonplaceholder.typicode.com/posts”端点。该函数将请求头设置为指示内容类型为JSON,并以JSON格式发送帖子数据。我们还显示成功状态。
<html>
<body>
<h2><i>POST</i> request example</h2>
<input type = "text" id = "title" placeholder = "Enter post title">
<br> <br>
<textarea id = "body" placeholder = "Enter post body"></textarea><br>
<br>
<button onclick = "sendPostRequest()">Submit</button> <br> <br>
<div id = "response" ></div>
<script>
function sendPostRequest() {
var postData = {
title: document.getElementById("title").value,
body: document.getElementById("body").value
};
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(postData));
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 201) {
document.getElementById("response").innerHTML = "Post request successful: " + xhr.responseText;
} else {
document.getElementById("response").innerHTML = "Post request failed: " + xhr.responseText;
}
};
}
</script>
</body>
</html>
用Fetch进行POST请求
fetch 是一种用于进行网络请求的现代方法。它通过传递URL和一个选项对象作为参数来发送POST请求。选项对象指定请求方法为”POST”,并将头部”Content-Type”设置为”application/json”。请求数据以字符串化的JSON对象形式传递在选项对象的body属性中。服务器返回的响应会使用.then()方法进行处理,该方法从响应中返回JSON数据。
示例
下面的示例演示了使用fetch发送POST请求。一个简单的表单发送POST请求到一个JSON占位符API。提交后,响应数据将以格式化的形式显示在HTML pre标签中。
<html>
<body>
<h2>Create New Blog Post:</h2>
<form>
<input type = "text" id = "title" placeholder = "Title" required>
<textarea id = "body" placeholder = "Body" required> </textarea>
<button type = "button" id = "submitBtn"> Submit </button>
</form> <br>
<h2>Response:</h2>
<pre id = "response" ></pre>
<script>
document.getElementById("submitBtn").addEventListener("click", function() {
let title = document.getElementById("title").value;
let body = document.getElementById("body").value;
let data = {
title: title,
body: body
};
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
document.getElementById("response").innerHTML = JSON.stringify(
data,
null,
2
);
});
});
</script>
</body>
</html>
我们已经学会使用JavaScript的XMLHttpRequest对象和使用fetch来进行Ajax调用的HTTP GET或POST,并提供了不同的示例。
极客笔记