如何使用Html Anchor <a>发送AJAX Post Request

Ras*_*ooq 0 javascript ajax jquery

我使用以下标记让用户喜欢这个帖子

<a href="#" class="like" id="like_22">Like</a>
Run Code Online (Sandbox Code Playgroud)

我得到了<a>通过Javascript 的id,它实际上是post_id,并like.php使用以下GET方法发送数据.

 post_id = 22;
 xrequest.open("GET","like.php?post_id="+post_id+",true);
 xrequest.send();
Run Code Online (Sandbox Code Playgroud)

我有两个问题

  1. 如何使用POSTMethod 发送此请求?
    (请注意,<form>...</form>标签周围没有任何标签.)
  2. 如果我使用上面提到的GET方法,它是否安全?

tec*_*bar 5

既然你已经标记了jQuery,我假设你正在使用它.如果是这样,你可以这样做:

// 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;
});
Run Code Online (Sandbox Code Playgroud)

关于你的第二个问题:,除非你在SSL(https)中这样做,否则它并没有真正使它更安全.一个中间人仍然可以在中途拦截你的信息并阅读内容.POST比GET更间接(拦截和读取有效负载),但不是更安全.