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

js get请求

作者:枫尘于往逝   发布日期:2026-01-09   浏览:65

// 使用 XMLHttpRequest 发起 GET 请求
function sendGetRequest(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 请求并处理响应
sendGetRequest('https://jsonplaceholder.typicode.com/posts/1', function(response) {
    console.log('Response:', response);
});

// 使用 Fetch API 发起 GET 请求(推荐)
fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json(); // 将响应体解析为 JSON
    })
    .then(data => {
        console.log('Data:', data); // 处理返回的数据
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });

解释说明:

  1. XMLHttpRequest:

    • 这是传统的发起 HTTP 请求的方式。
    • xhr.open("GET", url, true) 用于设置请求方法、URL 和是否异步。
    • xhr.onreadystatechange 用于监听请求状态的变化,当 readyState 为 4 并且 status 为 200 时,表示请求成功,可以处理响应数据。
  2. Fetch API:

    • 这是现代浏览器推荐的发起 HTTP 请求的方式,支持 Promise,语法更加简洁。
    • fetch(url) 发起请求,返回一个 Promise。
    • .then(response => response.json()) 将响应体解析为 JSON 格式。
    • .catch(error => {...}) 捕获请求过程中可能发生的错误。

上一篇:js domcontentloaded

下一篇:js arraybuffer

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

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

Laravel 中文站