V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
hiugo
V2EX  ›  问与答

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

  •  
  •   hiugo · 2022-09-08 17:52:01 +08:00 · 755 次点击
    这是一个创建于 588 天前的主题,其中的信息可能已经有所发展或是发生改变。

    栗子:

    <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 条回复    2022-09-11 18:44:15 +08:00
    zcf0508
        1
    zcf0508  
       2022-09-08 18:03:39 +08:00
    const nodes = document.querySelectorAll('p')

    nodes.map((node)=>{

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

    node.innerText = "结果"

    })
    Mexion
        2
    Mexion  
       2022-09-08 18:06:09 +08:00
    先获取到这个 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);
    Mexion
        3
    Mexion  
       2022-09-08 18:08:46 +08:00
    打错了,应该是:
    el.innerText
    多个的话就按一楼那样遍历就行了
    thefck
        4
    thefck  
       2022-09-08 18:14:35 +08:00
    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  
       2022-09-08 18:15:55 +08:00
    拿到 id 后,用 fetch 或 axios 向接口发请求即可获得返回数据,然后用 innerText 或 jquery 修改网页即可。

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

    好像没法在 wikijs 上用
    wdssmq
        7
    wdssmq  
       2022-09-11 18:44:15 +08:00
    document.querySelectorAll('p') 拿到的东西并不能直接遍历,是 NodeList

    @thefck
    @yuner4827

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

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

    [id:114514]

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

    这可能已经不是交流层面的问题了,,建议直接外包。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5606 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 06:27 · PVG 14:27 · LAX 23:27 · JFK 02:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.