开发者

Is it a good idea to make an AJAX call on <a> click before taking the user to the href location?

I have a few scenarios where on a click of <a> element on a page I need to send some data to the server with AJAX and if everything is fine take the user to where <a> is pointing. Here is the flow:

  1. User does something on the page.

  2. User clicks <a> element.

  3. AJAX call goes to the server, server processes the request, se开发者_如何学Pythonnds the response.

  4. If response is all good -> navigate, if some error -> return false from JavaScript, thus abort navigation and display error message.

So, I'm just wondering, is this generally a good or a bad practice and why?

Thank you.


There are no hard and fast rules regarding such issues, but one common rule of thumb is that <a> links shouldn't be used for POST-like actions such as updating a database. So ask yourself what the AJAX call does: if it simply requests some data from the server, it is okay to do this with an <a>; if it causes some sort of update to occur, consider using a <button> instead.


In the past, if a link has an onClick method, I've always done away w/ the href altogether. In your AJAX onClick method, just handle the logic within the method and, when needed, call Window.Location inside the method to load a new URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜