SCRIPT 专精提升:AJAX /# hash 动态网站/延时

发起AJAX请求

AJAX使用Script 内置,下面是DEMO GET与POST

注意:

// @grant GM_xmlhttpRequest
// @connect httpbin.org

上面两个 必须拥有 ,可以将GM_xmlhttpRequest封装成函数调用。

// ==UserScript==
// @name         AJAX DEMO GET-POST
// @namespace    https://docs.scriptcat.org/
// @version      0.1.0
// @description  try to take over the world!
// @author       You
// @match        https://el.psy.congroo.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=el.psy.congroo.com
// @grant        GM_xmlhttpRequest
// @connect      httpbin.org

// ==/UserScript==

(function() {
    'use strict';

// GET DEMO
    GM_xmlhttpRequest({
        method: "GET",
        url: "https://httpbin.org/get?name=Saya&to=lora",
        onload: function(response) {
            console.log('请求成功,状态码:', response.status);
            console.log('响应内容:', response.responseText);
        },
        onerror: function(error) {
            console.error('请求失败:', error);
        }
    });

// POST表单 传入 数据 JSON返回 DEMO
    const searchData = new URLSearchParams({
        keyword: "JavaScript教程",
        page: "1",
        sort: "latest",
        category: "编程"
    });

    GM_xmlhttpRequest({
        method: "POST",
        url: "https://httpbin.org/post",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        data: searchData.toString(),
        responseType: 'json',  // ✅ 加上这一行
        onload: function(res) {
            const results = res.response;
            // results 为队像直接处理
            console.log('搜索结果:json字符串', res.responseText);
            console.log('搜索结果:json对象', res.response);
        }
    });



    // Your code here...
})();

动态网站。# 访问 不刷新网页

hash事件监听【需要在监听函数创建后执行】
window.addEventListener(‘hashchange’, pageChanged);
自动调用函数pageChanged

关键变量参数,获取当前网页#后面的数据


    function pageChanged() {
        const hash = window.location.hash;
        console.log('当前页面:', hash || '首页');
        
        // 根据不同 hash 做不同事
        if (hash === '#/list') {
            console.log('📋 列表页,抓取数据...');
            // 你的抓取代码
        } else if (hash === '#/detail') {
            console.log('📄 详情页,抓取数据...');
            // 你的抓取代码
        }
    }



    // 首次加载执行
    pageChanged();

加上延时 动态网站必备

# 还是之前的change函数
// ============ 延迟包装 ============
let timer = null;

function pageChangedWithDelay(delay = 400) {
clearTimeout(timer);
timer = setTimeout(() => {
pageChanged();
}, delay);
}

// ============ 监听 ============
// ✅ hash 变化时自动调用
window.addEventListener('hashchange', pageChangedWithDelay);
此条目发表在None分类目录。将固定链接加入收藏夹。

发表回复