如何使用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检索数据,因为它们不会对服务器进行任何更改,因此被认为是安全且幂等的。
语法
用户可以按照以下语法使用javascript的“XMLHttpRequest”对象使用GET请求进行Ajax调用。
let xhr = new XMLHttpRequest();
xhr.open("GET", "URL", true);
xhr.send();
这将创建一个新的“XMLHttpRequest”对象并打开对给定URL的GET请求。最后,使用xhr.send()方法将GET请求发送到服务器。
请注意,您必须提供要从中检索数据的API URL。
示例
以下示例演示如何使用JavaScript向https://jsonplaceholder.typicode.com/posts API发出GET请求以检索数据。代码使用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()函数,该函数向“https://jsonplaceholder.typicode.com/posts”端点发出POST请求。该函数设置请求标头以指示内容类型为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请求。一个简单的表单向JSON占位符API发送POST请求。提交后,响应数据将使用HTML预标签进行格式化显示。
<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和不同的示例来使用HTTP GET或POST进行Ajax调用。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP