简体   繁体   English

为什么我不能使用AJAX发布JavaScript变量

[英]Why I can't use AJAX to post JavaScript variable

I am trying to pass JavaScript variables to the PHP file using the AJAX post method. 我正在尝试使用AJAX post方法将JavaScript变量传递给PHP文件。 My console returns: 'ok' , but if I enter a file.php , I have only display the white page. 我的控制台返回: 'ok' ,但是如果我输入file.php ,我只会显示白页。 Why? 为什么?

$(".btn_ranking").click(function(e) {
  e.preventDefault();

  var name = localStorage.getItem('name');
  var time = localStorage.getItem('timer_end');

  $.ajax({
    url: 'php/file.php',
    method: 'post',
    data: {
      name: name,
      time: time,
      success: function(response) {
        console.log('ok');
      }
    }
  });
});

<?php  

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

?>

One of the most important things to remember about Ajax is that it does not cause the browser to navigate to a new page . 关于Ajax要记住的最重要的事情之一是,它不会导致浏览器导航到新页面

The entire point of Ajax is that it makes an HTTP request and, instead of doing what the browser would normally do with the response, makes the response available to JavaScript. Ajax的全部要点是它发出一个HTTP请求,而不是使浏览器正常处理响应,而是使响应可用于JavaScript。


If you want to display the response to an Ajax request, then you have to write JavaScript that will display it. 如果要显示对Ajax请求的响应,则必须编写将显示该响应的JavaScript。

It will be available in the response variable (the first argument of the success method … which needs to be a property of the object you pass to ajax() and not a property of the data object … so how "OK" is showing up in your console, I have no idea). 它将在response变量中使用( success方法的第一个参数…,它需要是传递给ajax()的对象的属性,而不是data对象的属性…因此,“ OK”如何显示在您的控制台,我不知道)。

You can then add it to the document ( $(document.body).append(response) as a simple example). 然后,您可以将其添加到文档中(作为简单示例, $(document.body).append(response) )。


That said, if you want to render it as a whole new document, the best approach is to not use Ajax in the first place. 就是说,如果您要将其呈现为一个全新的文档,最好的方法是首先不要使用Ajax

Create a form with the data in it, append it to the document, then submit it. 创建一个包含数据的表单,将其附加到文档中,然后提交。

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

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