简体   繁体   English

无法向同一页面发出Ajax异步发布请求

[英]Unable to make a ajax async post request to the same page

I'm trying to make an async call to the same page but for some reason, the async call is not being made and hence getting "userinfo" undefined error! 我正在尝试对同一页面进行异步调用,但是由于某种原因,没有进行异步调用,因此出现“ userinfo”未定义错误! could someone please tell me what I'm doing wrong in this thank you! 有人可以告诉我我在做什么错吗,谢谢!

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    $( document ).ready(function() {
    //getting location of the user and assigning it to the variable
      $.get("http://ipinfo.io", function (response) {
        var usercity=response.city;
        console.log(usercity);
        $.ajax({
          //no need to provide url since we are making async call on the same page 
          type: "post",
          data: {cityinfo:usercity},
        });
      }, "jsonp");
    });
</script>

<?php
session_start(); 
$usercity=$_POST['cityinfo'];
echo $usercity; 
?>

First, you make a regular request to the PHP page. 首先,您对PHP页面进行常规请求。 $_POST['cityinfo'] is undefined at this stage because you don't set it. $_POST['cityinfo']在此阶段未定义,因为您未设置它。 The page includes an error message telling you that. 该页面包含一条错误消息告诉您。

Second, you make a JSONP request to ipinfo.io, and call a callback function when you get a response. 其次,您向ipinfo.io发出JSONP请求,并在收到响应时调用回调函数。

Third, you make a second HTTP request to the PHP page. 第三,您向PHP页面发出第二个HTTP请求。 This time you do define $_POST['cityinfo'] . 这次您确实定义了$_POST['cityinfo'] You have no success handler to do anything at all with the response so, although $_POST['cityinfo']; 尽管$_POST['cityinfo'];尽管您没有success处理程序对响应任何事情$_POST['cityinfo']; is set, you don't see any effect of that (unless you were to use the developer tools Network tab to examine the response itself). 设置,您将看不到任何效果(除非您使用开发人员工具的“网络”标签来检查响应本身)。

It is important to note that this is a second, distinct request to the same URL. 重要的是要注意,这是对同一URL的第二个不同请求。 The JavaScript does not travel back through time and set the $_POST['cityinfo']; JavaScript不会穿越时间并设置$_POST['cityinfo']; variable in the previous request (and it is the response to the previous request that is still displayed in the browser window). 前一个请求中的变量(并且是对前一个请求的响应,该响应仍显示在浏览器窗口中)。

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

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