jQuery: How do I POST on CLICK?

2019-06-07 23:08发布

问题:

I'm trying to figure out how I can pass data from page-list.php to page.php using jQuery .post() and .click().

Code in <head> of page-list.php:

<script type="text/javascript">
$(document).ready(function(){
    $('button.link').click(function () {
        $.post("page.php", {pageID: "1"} );
    }
});
</script>

Code in <body> of page-list.php:

<button class="btn link">LINK</button>

When I click LINK, nothing happens.

I'm also not sure how to call the posted data on page.php. Should I create a variable in PHP like this?

$pageID = ($_POST['pageID']);

And then call it in the body like this?

echo $pageID;

回答1:

If I understand correctly what you are trying to do is $.post() a variable to "page.php" and then redirecting to "page.php".

If that is what you are trying to do it just won't work. $_POST requests are independent of each other, i.e. using $.post, accessing $_POST['pageID'] will result in whatever value you sent but won't display anything because the browser was not sent to the new page with the variables; but redirecting and trying to access the same variable will result in "null".

It is that same reason that when you use a log in system and refresh the page right afterwards the browser confirms that you want to send the information again.

Using $_GET might be more of what you need. Another option would be to use and form to post the variables.

I hope that helps.



回答2:

For one thing you are missing a couple of characters.

<script type="text/javascript">
$(document).ready(function(){
    $('button.link').click(function () {
        $.post("page.php", {pageID: "1"} );
    }); // missing end of statement.
});
</script>