简体   繁体   中英

JQuery call function from hyperlink

In JSP / JQUERY, I am creating a dynamic list of hyperlinks within a listview. Rather than pass sensitive information as GET parameters back to the server, I want a click on the hyperlinks to call a function where I can pass in the parameters, and then do a POST.

Here is the relevent section of code where the list is generated:

        <!-- Page -->
    <div data-role="page" data-add-back-btn="false">

        <!-- Content -->
        <div data-role="content" data-theme="c">
            <ul data-role="listview" data-inset="true" data-filter="true" data-autodividers="false">
                <%
                    for (int i=0; i<srVector.size(); i++) {
                        sr = (SR)srVector.get(i);
                %>
                    <li>
                        <a href="/myServlet?cmd=getDetails&srId=<%=sr.SR_ID%>&empCode=<%=empCode%>"><h3><%=sr.ACCT_NAME%></h3></a>
                    </li>
                <%
                    } 
                %>
            </ul>
        </div> <!-- End Content -->

Would appreciate any help.

You can do it like that:

Your anchor:

// you can use whatever selector you like
// this example use [data-post-link] attribute
<a href="url/to/send/to" data-post-link="send-form" data-id="<%=sr.SR_ID%>">send me</a>

Binding jquery callback to the anchor:

// you can use whatever selector you like
$('[data-post-link]').on('click', function() {
  send(this);
});

and this is the send function:

var send = function(element) {
  var value = {
    // you can put any data you want
    'id': $(element).attr('data-id')
  };

  $.ajax({
    type: "POST",
    url: $(element).attr('href'),
    data: value // value object created above
  });
};

But, your sensitive data will be exposed anyway, because this way you have to print it in your markup and anyone can see it.

And even if not, then someone can just see it in your js callback function body.

There are two options:

  • This data isn't sensitive really (is it? can someone hack your app using those data? steal something? make some unintended use of it?)

  • In case if the answer is "yes", than you should validate if data is coming "really" from you. Just don't implement it your self. Your framework of choice for sure has build in CSRF protection mechanism. Here is a link to the documentation about it in spring framework: Spring framework CSRF

You didn't say what framework you use, but it should be easy to google for any framework.

Also here is a CSRF protection filter for pure JSP servlets - OWASP CSRFGuard Project. (Installation and configuration is at the bottom of the site.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM