要从javascript函数调用servlet,请在onClick事件上调用,而无需在'href'

To call servlet from javascript function, called on onClick event without redicting page to link in 'href'

本文关键字:href servlet 函数调用 javascript 请在 onClick 要从 事件 调用      更新时间:2023-09-26

我有一个带有href和onClick事件的标记。我想执行为onClick事件指定的函数,然后将页面重定向到href中的链接。但是,当我从该函数调用servlet时,页面会重定向到href中的链接,而不是servlet。我想先在servlet中完成处理,然后将该页面重定向到href-lin。能做些什么?

<a href="http://www.google.com" onclick="createHttpRequest(this); return true; ">Google</a>

这是用于调用servlet的javascript函数。

function createHttpRequest(obj)
{
    link=obj.href;
    if(typeof XMLHttpRequest != "undefined") {
        request = new XMLHttpRequest();     
    } 
    else if(window.ActiveXObject)   {
        request = new ActiveXObject("Msxml2.XMLHTTP");
        if(!request) {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    if(request) {
        url="http://localhost:8080/HitCounter/InsertCount?sent_url="+link;
        request.onreadystatechange = handleRequest;
        request.open("GET",url,true);
        request.send(null);
        }
    else {
        alert("error on Page createHttpRequest");
    }   
    return true;
}
return true;

应该是

return false;

onclick属性和方法中,return false会阻止默认操作(即跟随链接)。