jsp-如何在javascript函数中复制URL?

时间:2019-03-19 07:01:10

标签: javascript jsp

我有一个看起来像这样的JSP页面:

enter image description here

我添加了一个按钮Copy URL,这是不言而喻的,当我单击该按钮时,我需要为该特定链接本身复制唯一的URL。

这是我前端的外观:

<%
    //need to input logic to populate data on each row

    int counter=0;

    String[] split = request.getParameter("nodeID").split(",",0);
    for(int i=0;i<split.length;i++){

        long file=Long.parseLong(split[i]);

        List files = fileFacade.list_items(file);
        for (Iterator rstltr = files.iterator(); rstltr.hasNext();) {
            Fmedia fv = (Fmedia) rstltr.next();
            Node nd = nodeFacade.get(fv.getNodeid(), false);
            // Fmedia fm = fileFacade.get_file(fv.getNodeid());

            int count = 0;
            count++;
            long fileid= nd.getNodeid();



%>


    <tbody>
        <tr>
            <td width="5%">
                <!--Display Checkbox   -->
                <input type="checkbox" name="name1" />&nbsp;
            </td>

            <td>
                <!--Display No   -->
                <% counter=counter+1;
                    out.print(counter);

                %>


            </td>
            <td width="28%">

                <!-- Display Filename   -->
                <%=nd.getNodedesc()%>



            </td>
            <td width="100%">
                <!-- Display URL -->


                <%="http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+nd.getNodeid()%>
                <%

                    fileFacade.insert_url(nd.getNodeid(),"http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+nd.getNodeid());


                %>


            </td>
            <td>
                <!-- Display EDIT/DEL -->

            </td>
            <td> <!-- Display COPY feature -->

                <input type="button" value="Copy URL" onclick="msg()">
                <script>
                    function msg() {
                        alert("Hello world!");
                    }
                </script>
            </td>


        </tr>

        </tbody>


    <%}}
    %>

我需要一种方法,使每个按钮独立于每一行,并且需要一个javascript函数,以便能够在选中复选框后复制链接。

我不太确定如何从这里开始。

有人可以建议一个好的方法吗?

编辑:

JavaScript函数:

<input type="button" value="Copy URL" onclick="getURL()">
            <script>
                function getURL() {
                    var copyText = "http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+<%nd.getNodeid();%>
                    var el = document.createElement('textarea');
                    el.value = copyText;
                    el.setAttribute('readonly', '');
                    el.style = {
                        position: 'absolute',
                        left: '-9999px'
                    };
                    document.body.appendChild(el);
                    el.select();
                    document.execCommand('copy');
                    document.body.removeChild(el);
                }
            </script>
        </td>

1 个答案:

答案 0 :(得分:1)

您必须将URL传递给函数,请遵循以下代码

import asyncio
import os
from uuid import uuid4
import json
from dataclasses import dataclass

from tornado.escape import json_encode, json_decode, url_escape
from tornado.websocket import websocket_connect
from tornado.httpclient import AsyncHTTPClient, HTTPRequest

client = AsyncHTTPClient()
session_id = 'faf69f76-6667-45d6-a38f-32460e5d7f24'
token = 'e9e267d0c802017c22bc31d276b675b4f5b3e0f180eb5c8b'
kernel_id = 'fad149a5-1f78-4827-ba7c-f1fde844f0b2'

@dataclass
class Cell:
    code: str
    index: int
    execution_count: int

# We keep track of all cells to matain an updated index
cells = []

async def get_sessions():
    url = 'http://localhost:8888/api/sessions?token={}'.format(token)
    req = HTTPRequest(url=url)
    resp = await client.fetch(req)
    print(resp)
    print(resp.body)

async def get_notebook_content(path):
    url = 'http://localhost:8888/api/contents/{}?token={}'.format(path, token)

    req = HTTPRequest(url=url)
    resp = await client.fetch(req)
    return json_decode(resp.body)

async def get_session(session_id):
    ses_url = 'http://localhost:8888/api/sessions/{}?token={}'.format(session_id, token)
    ses_req = HTTPRequest(url=ses_url)
    resp = await client.fetch(ses_req)
    return json_decode(resp.body)

# return the list of notebook cells as Cell @dataclass
def parse_cells(content):
    res = []
    # we iterate over notebook cells
    cells = content['content']['cells']
    # search the cell
    for index, c in enumerate(cells):
        cell_execution_count = c['execution_count']
        code = c['source']
        cell = Cell(code=code, index=index, execution_count=cell_execution_count)

        res.append(cell)

    return res

# listen to all notebook messages
async def listen():
    session_data = await get_session(session_id)
    notebook_path = session_data['notebook']['path']
    notebook_content = await get_notebook_content(notebook_path)

    # parse existing cells
    cells = parse_cells(notebook_content)

    # listen to all messages
    req = HTTPRequest(
        url='ws://localhost:8888/api/kernels/{}/channels?token={}'.format(
            kernel_id,
            token))
    ws = await websocket_connect(req)
    print('Connected to kernel websocket')
    hist_msg_id = None

    while True:
        msg = await ws.read_message()
        msg = json_decode(msg)
        msg_type = msg['msg_type']
        parent_msg_id = msg['parent_header']['msg_id']

        if msg_type == 'execute_input':
            # after a executed cell we request the history (only of the last executed cell)
            hist_msg_id = uuid4().hex
            ws.write_message(json_encode({
                'header': {
                    'username': '',
                    'version': '5.3',
                    'session': '',
                    'msg_id': hist_msg_id,
                    'msg_type': 'history_request'
                },
                'parent_header': {},
                'channel': 'shell',
                'content': {
                    'output': False,
                    'raw': True,
                    'hist_access_type': 'tail',
                    'n': 1
                },
                'metadata': {
                },
                'buffers': {}
            }))
        elif parent_msg_id == hist_msg_id and msg_type == 'history_reply':
            # we receive the history of the last executed cell with his execution_count
            hist_msg_id = None # we dont expect more replies
            # see message type 'history_result': https://jupyter-client.readthedocs.io/en/latest/messaging.html#history
            execution_count = msg['content']['history'][0][1]
            code = msg['content']['history'][0][2]
            # update the existing cell
            for c in cells:
                if c.execution_count + 1 == execution_count:
                    c.code = code
                    c.execution_count = execution_count

                    print('# Cell changed: {}'.format(c))

if __name__ == '__main__':
    asyncio.run(listen())