<a> tag and get request

时间:2017-04-02 00:42:21

标签: node.js html5 get anchor

I have a perhaps simple question. What would be the difference between an <a> tag and a normal GET request with any element. I know the <a> tag automatically sends you to the url specified in its href attribute. So I assume that a Get request does something similar in it's success callback (as demonstrated below)

But let's say that I also want to send some information along with a normal get request when a for example <span> element is clicked on so I write:

   $('span').click(() => {
    $.ajax({
        url: '/someurl',
        type: 'GET',
        data: {
            title: someTitle,
            email: someEmail
        },
        success: (data) => {
                window.location = '/someurl';

        }
    });
});

Is there any way to achieve this with an <a> tag? Sending information to the server so it's available in req.query.title and req.query.email ?

Doing the ajax request above will run my app.get('/someurl',(req,res)=>{})twice because I am sending a GET request to send the data (title and email) and then I am making another GET request when I write window.location = '/someurl' How can I redo this so that it only sends the GET request ONCE but also allows for the sending and storing information to the req object AND ensures that the browser is now displaying /someurl.

2 个答案:

答案 0 :(得分:3)

只需在您放在<a>标记的href中的URL中创建相应的查询字符串,它就像您的ajax调用一样。假设someTitle的值为"The Hobbit"someEmail的值为foo@whatever.com,那么您可以像这样构建该网址:

<a href="/someurl?title=The%20Hobbit&email=foo%40whatever.com">Click Me</a>

必须在网址中转义许多非字母字符。在上面的网址中,空格将替换为%20,@替换为%40。在您的特定示例中,您可以打开Chrome调试器中的网络标签,查看Chrome为您的ajax呼叫发送的确切网址,将其复制到剪贴板并将其插入<a>标记。

这是一个表格,显示查询字符串组件(&之后或=之后的部分)必须替换哪些字符:

enter image description here

  

我只是想知道,除了语义原因,使用标签而不是其他任何东西还有其他好处吗?

各种可能会读取您网页的计算机都会理解

<a>标记,例如屏幕阅读器可以为您的网站编制索引。此外,它们可以自动使用浏览器键盘支持,按住Ctrl键单击以打开新选项卡。而一段Javascript可能不会自动支持任何该功能。因此,基本上,如果<a>标签可以满足您的需求,那么它就是首选,因为它具有许多其他默认功能,对用户来说是必要或便利的。

答案 1 :(得分:2)

<a href="/someurl?title=Hello&email=tom%40home.com">Hello</a>