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

时间:2019-01-03 22:32:17

标签: php ajax

我正在尝试对同一页面进行异步调用,但是由于某种原因,没有进行异步调用,因此出现“ userinfo”未定义错误!有人可以告诉我我在做什么错吗谢谢你!

<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; 
?>

1 个答案:

答案 0 :(得分:1)

首先,您对PHP页面进行常规请求。 $_POST['cityinfo']在此阶段未定义,因为您没有设置它。该页面包含一条错误消息告诉您。

第二,您向ipinfo.io发出JSONP请求,并在收到响应时调用回调函数。

第三,您向PHP页面发出第二个HTTP请求。这次您要定义$_POST['cityinfo']。您根本没有success处理程序来对响应进行任何操作,因此,尽管设置了$_POST['cityinfo'];,您仍然看不到任何效果(除非您要使用开发人员工具的“网络”标签来检查响应本身)。

请务必注意,这是对同一URL的第二个不同请求。 JavaScript不会随着时间的流逝而在上一个请求中设置$_POST['cityinfo'];变量(它是对前一个请求的响应,该变量仍显示在浏览器窗口中)。

相关问题