jQuery: How do I POST on CLICK?

為{幸葍}努か 提交于 2019-12-08 03:57:56

问题


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>


来源:https://stackoverflow.com/questions/8115119/jquery-how-do-i-post-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!