window.location似乎取消了ajax post请求 [英] window.location seems to cancel ajax post request

查看:109
本文介绍了window.location似乎取消了ajax post请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用ajax发送数据到php,同时重定向到那个php文件,但是当我重定向到php文件时,ajax似乎没有发送数据。我想实现点击一个按钮,并使用ajax将数据发送到php,同时重定向到该php文件以查看通过显示发送的数据。我没有使用像 window.location =ajaxtest.php?data = data之类的原因是因为我会在google map api中使用它如果我点击某个地方的按钮,那么我将重定向到地图页面,并根据发送到php文件的ajax的id以及基于该id生成的坐标显示特定位置的标记。

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

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

ajaxtest.php

<?php  

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

?>


推荐答案

所以,这不是HTTP,AJAX或PHP工作。当您进行重定向时,没有任何POST数据,因为重定向是来自AJAX帖子的单独请求。你想要的是做一个AJAX帖子,并以某种方式消耗你的页面上的响应,根本不做重定向。

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.

这篇关于window.location似乎取消了ajax post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆