开发者

Need to add function

I'd like to add a simple functionality to my pages, where a user will see a "follow" button and by clicking it a db record will be created (userID and pageID). I'll handle query on the backend, I suppose. I think I need to do it in AJAX, but I havebn't done much with AJAX. I was also thinking that updating the button status from FOLLOW to FOLLOWING (or something similar) I could do with jQuery, with so开发者_如何学Cme sort of toggle, while the request is being processed on the background.

Am I on the right track with this?


You're on the right track.

I've created an example which uses a button like <input type="image" class="follow">. When I user clicks on it it sends a request to the server (url). On success it updates the button image.

  $('input[type=image].follow').click(function() {
    var button = $(this);
    var current_img = $(button).attr('src');
    var current_alt = $(button).attr('alt');

    $(button).attr('src', '/style/icons/ajax-loader.gif');
    $(button).attr('alt', 'Requesting data from the server...');

    $.ajax({
      url: url of script the processes stuff (like db update),
      type: 'POST',
      data: {},
      dataType: "json",
      error: function(req, resulttype, exc)
      {
        $(button).attr('src', '/style/error.png');
        $(button).attr('alt', 'Error while updating!');
        window.setTimeout(function() {
          $(button).attr('src', current_img);
          $(button).attr('alt', current_alt);
        }, 3000);
      },
      success: function(data)
      {
        $(button).attr('src', '/style/followed.png');
        $(button).attr('alt', 'Followed');
      }
    });

    return false;
  });

Above is just some example code. Change it at your will. Have fun with it.


AJAX is right, jQuery makes ajax easy.

//Post with jQuery (call test.php):
$.post('test.php', function(data) {
  //Do something with result data
});


It sounds like you are on the right track here. If you're working with a smaller application then using an AJAX request and creating your record would be easiest using a Java servlet and putting for example some JDBC code in your doGet or doPost method to perform the database operations. At the same time your onSuccess method for your AJAX request can call the jQuery code necessary to update your button. Good Luck!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜