hiugo
V2EX  ›  问与答

想请教一下 js 如何获取<p id="">中 id 的内容并请求指定地址获取返回数据赋值给 p 标签?

  •  
  •   hiugo · Sep 8, 2022 · 1714 views
    This topic created in 1361 days ago, the information mentioned may be changed or developed.

    栗子:

    <p id="114514"></p>

    接口是https://aaa.com/name?=114514 返回数据是 “田所浩二” 那么应该怎么让js携带id中的参数去请求https://aaa.com/name?=114514 然后把返回的“田所浩二”赋值给p 标签

    有大佬能给个栗子吗? 接口是 https://bilibili.vuplive.com/name.php?uid=114514

    7 replies    2022-09-11 18:44:15 +08:00
    zcf0508
        1
    zcf0508  
       Sep 8, 2022
    const nodes = document.querySelectorAll('p')

    nodes.map((node)=>{

    const id = node.id
    // 请求拿数据

    node.innerText = "结果"

    })
    Wanex
        2
    Wanex  
       Sep 8, 2022
    先获取到这个 id:
    const el = document.querySelector("p");
    const id = el.id;
    然后直接请求替换就行了:
    fetch(`https://bilibili.vuplive.com/name.php?uid=${id}`).then(res => res.text()).then(res => p.innerText = res);
    Wanex
        3
    Wanex  
       Sep 8, 2022
    打错了,应该是:
    el.innerText
    多个的话就按一楼那样遍历就行了
    thefck
        4
    thefck  
       Sep 8, 2022
    document.querySelectorAll('p').forEach(function(node){
    if(node.id){
    var xhr = new XMLHttpRequest();
    xhr.open('get', 'https://bilibili.vuplive.com/name.php?uid='+node.id);
    xhr.onreadystatechange = function () {
    if (xhr.readyState !== 4) return;
    if (xhr.status === 200) {
    node.innerText = xhr.responseText
    }
    };
    xhr.send();
    }
    })
    cmdOptionKana
        5
    cmdOptionKana  
       Sep 8, 2022
    拿到 id 后,用 fetch 或 axios 向接口发请求即可获得返回数据,然后用 innerText 或 jquery 修改网页即可。

    而怎么拿到 id ,就要找规律了,比如是不是整个网页只有一个 <p>, 或者是不是有一堆 <p> 在某个 <div> 内等等。
    hiugo
        6
    hiugo  
    OP
       Sep 8, 2022
    @thefck
    ![90xnR.png]( https://s1.328888.xyz/2022/09/08/90xnR.png)

    好像没法在 wikijs 上用
    wdssmq
        7
    wdssmq  
       Sep 11, 2022
    document.querySelectorAll('p') 拿到的东西并不能直接遍历,是 NodeList

    @thefck
    @yuner4827

    然后,看截图是个文本编辑器,源码下只是个字符串,渲染后也是在 iframe 内的(以一般富文本编辑器而论),也并不和真正的文本框双向绑定;

    以一般编辑器的机制,所见即所得模式下输入:

    [id:114514]

    JS 提取文本框内容,解析识别后调用 API 写入回去可能更合理,如果有暴露 API 的话;

    这可能已经不是交流层面的问题了,,建议直接外包。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5582 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 08:20 · PVG 16:20 · LAX 01:20 · JFK 04:20
    ♥ Do have faith in what you're doing.