简体   繁体   English

如何使用ajax在其他.php文件上传递此变量

[英]How to pass this variable on other .php file with ajax

I want to pass the id in posts.php with ajax and here in href i want to put "#". 我想使用ajax在posts.php中传递ID,在href中我想输入“#”。

When this link gets clicked, It goes to that link. 单击此链接后,将转到该链接。 But I dont want to go that link and at a same time i need to pass the id in posts.php. 但是我不想去那个链接,同时我需要在posts.php中传递ID。

How can I do this? 我怎样才能做到这一点?

<li><a href="posts.php?id=<?=$post_id?>" >post</a></li>

Could do something like this: 可以做这样的事情:

HTML : HTML

<li><button type="button" id="pass-data" data-postid="<?= $post_id; ?>">Click me</button></li>

jQuery : jQuery的

$("#pass-data").click(function(){ // on button click
    var dataid = $(this).attr("data-postid"); // get post id

    $.ajax({
        method: "POST",
        url: "posts.php", // page to post data to
        data: { id: dataid }, // the post_id (you can access it with $_POST["id"])
        success: function(){ // if successful
            alert("Success!"); // alert "success!"
        }
    });
});

Like this - note the preventDefault that stops the link: 这样-注意停止链接的preventDefault:

<li><a class="postLink" href="posts.php?id=<?=$post_id?>" >post</a></li>

$(function() {
  $(".postLink").on("click",function(e) {
    e.preventDefault(); // cancel link
    $.post(this.href,function(data) {
      console.log("Posted the link, returned:",data);
    });
  });
});

OR 要么

<li><a class="postLink" href="#" data-id="<?=$post_id?>">post</a></li>

$(function() {
  $(".postLink").on("click",function(e) {
    e.preventDefault(); // cancel link
    $.post("posts.php",{"id":$(this).data("id")},function(data) {
      console.log("Posted the link, returned:",data);
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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