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

js 网络请求

作者:寂寞味道   发布日期:2025-08-09   浏览:81

// 使用 XMLHttpRequest 进行简单的 GET 请求
function sendGetRequest(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 请求成功,调用回调函数并传递响应文本
            callback(xhr.responseText);
        }
    };
    xhr.open("GET", url, true);
    xhr.send();
}

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

// 使用 Fetch API 进行 GET 请求
async function fetchGetData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const data = await response.json();
        console.log('Fetched Data:', data);
    } catch (error) {
        console.error('Fetch Error:', error);
    }
}

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

// 使用 Fetch API 进行 POST 请求
async function fetchPostData(url, data) {
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const responseData = await response.json();
        console.log('Posted Data:', responseData);
    } catch (error) {
        console.error('Fetch Error:', error);
    }
}

// 示例:使用 Fetch API 发送 POST 请求
const postData = { title: 'foo', body: 'bar', userId: 1 };
fetchPostData('https://jsonplaceholder.typicode.com/posts', postData);

解释说明:

  1. XMLHttpRequest:

    • sendGetRequest 函数展示了如何使用 XMLHttpRequest 对象发送一个简单的 GET 请求。
    • 当请求完成并且状态码为 200 时,会调用回调函数并传递响应文本。
  2. Fetch API:

    • fetchGetData 函数展示了如何使用现代的 Fetch API 发送 GET 请求,并处理响应数据。
    • fetchPostData 函数展示了如何使用 Fetch API 发送 POST 请求,并传递 JSON 数据。
    • Fetch API 是一种更现代化、更灵活的方式来进行网络请求,支持 Promise 和 async/await 语法,代码更加简洁和易读。

上一篇:js switch语法

下一篇:js click方法

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

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

Laravel 中文站