最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Html Anchor <a> to send AJAX Post Request - Stack Overflow

programmeradmin0浏览0评论

I am using the following tag to let the users like the post

<a href="#" class="like" id="like_22">Like</a>

I get the id of the <a> through Javascript which is actually the post_id and send the data to like.php using the following GET method.

 post_id = 22;
 xrequest.open("GET","like.php?post_id="+post_id+",true);
 xrequest.send();

I have two questions

  1. How can I send this request using POST Method?
    (Note that there is not any <form>...</form> around the tag.)
  2. If I use the above mentioned GET Method, Is it secure?

I am using the following tag to let the users like the post

<a href="#" class="like" id="like_22">Like</a>

I get the id of the <a> through Javascript which is actually the post_id and send the data to like.php using the following GET method.

 post_id = 22;
 xrequest.open("GET","like.php?post_id="+post_id+",true);
 xrequest.send();

I have two questions

  1. How can I send this request using POST Method?
    (Note that there is not any <form>...</form> around the tag.)
  2. If I use the above mentioned GET Method, Is it secure?
Share Improve this question edited Apr 24, 2013 at 14:47 Antony 15.1k10 gold badges47 silver badges76 bronze badges asked Apr 24, 2013 at 14:42 Rashid FarooqRashid Farooq 3655 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Since you've tagged jQuery, I assume you are using it. If so, you can do it like:

// attach a click handler for all links with class "like"
$('a.like').click(function() {

    // use jQuery's $.post, to send the request
    // the second argument is the request data
    $.post('like.php', {post_id: this.id}, function(data) {
        // data is what your server returns
    });

    // prevent the link's default behavior
    return false;
});

Regarding your second question: No, it does not really make it safer unless you are doing it within SSL (https). a middle-man can still intercept your message mid-way and read the contents. POST makes it more indirect (to intercept and read the payload) than GET, but not safer.

To use POST to send the like link id you can do the following:

    $(document).ready(function() {
    $("a.like").click(function(event) {
        var data = event.target.id;
        $.ajax({
        type: "POST",
        url: "like.php",
        data: data
        });
    });
    });

updated, there was a typo in my code.

If i understand your question correctly, something like this should work for you:

$('#link_22').click(function(){
    var link = $(this).attr('id');
    $.post('/like.php/', {post_id: link});
    return false;

})

Then you can reach this from PHP with something like:

$_POST['post_id'];
发布评论

评论列表(0)

  1. 暂无评论