php 如何使用jQuery在同一页面中将值POST到PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8220950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:11:20  来源:igfitidea点击:

How to POST value to PHP in the same page using jQuery

phpjquery

提问by Indy

I don't know if I'm just dumb. I have been trying to figure this out for the past 1hour. Please help!!

我不知道我是不是傻。在过去的 1 小时里,我一直在努力解决这个问题。请帮忙!!

     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery.js" type="text/javascript"></script>
</head>

<body>
<div id="box" ></div>
<div id="box2"></div>

<script type="text/javascript">
  $(function(){
  $('#box').html("Test");

    //$('#box').attr('name','Indy');
    //var a= $('#box').attr('name');
    $.post(window.location, {name: 'John'});


});

</script>
</body>
</html>
<?php
print_r($_POST);
?>

How do I pass the value? I know this works if the php is in a different file. But this is not the case here.

我如何传递值?我知道如果 php 位于不同的文件中,这会起作用。但这里的情况并非如此。

回答by Blender

You won't be seeing the request's results because $.post()and all the AJAX functions run in the background, which doesn't refresh the page.

您不会看到请求的结果,因为$.post()所有 AJAX 函数都在后台运行,不会刷新页面。

As for posting to the current page, just use the window's location:

至于发布到当前页面,只需使用窗口的位置:

$.post(window.location, {name: 'John'}, function(data) {
  alert('POST was successful. Server says: ' + data);
});

回答by daniel0mullins

The $.post is an asynchronous posting the the same php file. You aren't going to see anything in the body of your page because

$.post 是异步发布相同的 php 文件。您不会在页面正文中看到任何内容,因为

<?php
print_r($_POST);
?>

Is after the </html>tag.

是在</html>标签之后。

If you are wanting to post something to the php file, and then process it and have the results show up in the page, simply create a form that actually POSTs to the php file. AJAX isn't always the right answer.

如果您想将某些内容发布到 php 文件,然后对其进行处理并将结果显示在页面中,只需创建一个实际发布到 php 文件的表单即可。AJAX 并不总是正确的答案。

回答by wargodz009

you can try inserting this into your javascript code:

您可以尝试将其插入到您的 javascript 代码中:

 $('some_button').click(function(){
      window.location = "http://your_site/page.php?name=John&var2="+param2;
 });

what this code do is adding some parameter into url and you can access that in your php page using GET. for example:

这段代码的作用是将一些参数添加到 url 中,您可以使用 GET 在您的 php 页面中访问它。例如:

 if(isset($_GET['name'])){
      echo $_GET['name'];
 }