简体   繁体   English

返回当前页面时不显示jQuery ajax响应

[英]jQuery ajax response not displaying when returning to current page

I'm attempting to post some data back to the same page through ajax. 我正在尝试通过ajax将一些数据发布回同一页。 In the example below the $name variable is not being updated in my page once the button is clicked. 在下面的示例中,单击按钮后,不会在我的页面中更新$name变量。 However, if I look at the console log of the response from ajax (using firebug) it shows the correct html, with the name inserted (ie <div>Matthew</div> ) - the page just isn't being updated with this response. 但是,如果我查看来自ajax的响应的控制台日志(使用firebug),则会显示正确的html,并插入名称(即<div>Matthew</div> )-该页面不会被更新响应。 Any ideas for how to fix this would be greatly appreciated. 任何有关如何解决此问题的想法将不胜感激。

The code I have is: 我的代码是:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>

<?php
$name = "A name";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $name = "No name!";
  }
  else{
    $name = $_POST["name"];
  }
}
?>

<script>
$(document).ready(function(){
    $("button").click(function(){ 
       var mydata = {name: "Matthew"}; 
       $.ajax({
          type: 'POST',
          data: mydata,
          success: function(data){
            console.log(data);
          }
        });

    });
});
</script>

<button>Send an HTTP POST request to a page and get the result back</button>

<div id="name">
<?php echo $name;?>
</div>

</body>
</html>

It is because <?php echo $name;?> does not run again when doing the ajax call. 这是因为<?php echo $name;?>在执行ajax调用时不会再次运行。 You have to replace the content of the div in the success function like this: 您必须像这样在成功函数中替换div的内容:

success: function(data){
            $("div").html(data);
          }

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

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