Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
758 views
in Technique[技术] by (71.8m points)

javascript - window.location seems to cancel ajax post request

I am trying to send data to php with ajax and at the same time redirect to that php file but when I redirected to the php file, the ajax didn't seem to send the data. I wanted to achieve something wherein a button is clicked and a data is sent to php using ajax and at the same time redirect to that php file to see the data sent by displaying it. The reason I didn't use something like window.location="ajaxtest.php?data=data" is because I'm gonna be using it in a google map api wherein if I click a button of a place, then I will redirect to the maps page and display the marker of the specific place depending on the id the ajax sent to the php file and the coordinates generated based on that id.

ajaxtest.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3
/jquery.min.js"></script>
<script>

    $(document).ready(function(){
        $("#button").click(function(){
            var data = "test";
            $.post("ajaxtest.php",{
                 data: data
            },function(data, status){
                 window.location="ajaxtest.php";
            });
        });
    });

</script>

<button id="button">test</button>
</body>
</html>

ajaxtest.php

<?php  

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

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So, that's not how HTTP, AJAX, or PHP work. There isn't any POST data when you do your redirect, because the redirect is a separate request from the AJAX post. What you want is to do an AJAX post and somehow consume the response on your page, without doing a redirect at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...