简体   繁体   中英

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. My console returns: 'ok' , but if I enter a file.php , I have only display the white page. 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 .

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.


If you want to display the response to an Ajax request, then you have to write JavaScript that will display it.

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).

You can then add it to the document ( $(document.body).append(response) as a simple example).


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.

Create a form with the data in it, append it to the document, then submit it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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