用js写一个request请求
时间: 2023-05-21 18:03:02 浏览: 74
可以使用XMLHttpRequest对象来发送request请求,以下是一个简单的示例代码:
```
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
```
这段代码会发送一个GET请求到http://example.com/api/data,并在请求完成后打印响应内容。你可以根据需要修改请求方法、请求地址和请求参数。
相关问题
原生js写一个登录请求
可以使用 XMLHttpRequest 对象发送登录请求。
例如:
```
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
request.open("POST", "/login", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("username=USERNAME&password=PASSWORD");
```
在这个例子中,我们使用 POST 方法发送了一个登录请求到 "/login" 路径,并在请求体中包含了用户名和密码。
当服务器返回响应时,我们会在控制台中输出响应文本。
如何用Javascript写个http请求?
可以使用XMLHttpRequest对象来进行HTTP请求。以下是一个简单的使用XMLHttpRequest对象发送GET请求的示例:
```javascript
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
```
在这个示例中,我们创建了一个XMLHttpRequest对象,然后使用open()方法打开了一个GET请求。第三个参数为true表示该请求是异步的。然后我们指定了一个回调函数,当请求完成时会自动调用该函数。在回调函数中,我们检查了请求的状态,如果成功,则打印出响应文本,否则打印出错误信息。最后,我们调用了send()方法,发送了请求。
你可以根据你的需求来修改请求的方法(GET或POST)、URL、请求头、请求体等等。