Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js request

作者:醉眼看苍生   发布日期:2026-05-31   浏览:107

// 使用 XMLHttpRequest 发起 GET 请求
function getRequest(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // 请求成功,调用回调函数处理响应数据
            callback(xhr.responseText);
        }
    };
    xhr.send();
}

// 示例:发起一个 GET 请求并打印响应结果
getRequest('https://jsonplaceholder.typicode.com/posts/1', function(response) {
    console.log('Response:', response);
});

// 使用 Fetch API 发起 GET 请求
function fetchRequest(url) {
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json(); // 解析 JSON 数据
        })
        .then(data => {
            console.log('Fetched data:', data); // 处理返回的数据
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
        });
}

// 示例:使用 Fetch API 发起请求
fetchRequest('https://jsonplaceholder.typicode.com/posts/1');

解释说明:

  1. XMLHttpRequest:

    • 这是较早的方式用于发起 HTTP 请求。
    • xhr.open() 方法用来初始化请求,xhr.send() 发送请求。
    • xhr.onreadystatechange 监听请求状态的变化,当 readyState 为 4(表示请求完成)且 status 为 200(表示请求成功)时,调用回调函数处理响应。
  2. Fetch API:

    • 这是现代浏览器推荐的方式,基于 Promise,语法更简洁。
    • fetch() 返回一个 Promise,可以链式调用 .then().catch() 来处理响应和错误。
    • response.json() 用来解析 JSON 格式的响应数据。

上一篇:js websocket框架

下一篇:js foreach 退出循环

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站