jQuery到PHP $ .post没有回显页面上的任何内容但是将数据回显到jQuery [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

PHP和jQuery“$ .post”正在制造麻烦。我在PHP文件中发布了一些变量。

jQuery是:

navigator.geolocation.getCurrentPosition(saveGeoLocation);
function saveGeoLocation(position) {
   var latitude = position.coords.latitude;
   var longitude = position.coords.longitude;   

   $.post("__g.php", { 
      latitude: latitude, 
      longitude: longitude 
   }).done(function(data) {
      console.log("Data Loaded: " + data);
   });

}

PHP是:

$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
echo "Position output: " . $latitude . $longitude;

控制台正在通过jQuery发送的所有信息正确显示回声。但是在页面本身上,PHP-echo只是回显引号内的内容而不是变量内容。

PHP位于单个文件中,但通过include()导入到更大的文件中。

(这是一个简化的例子,可能会有拼写错误。)

谢谢你的智慧!

- - - - - 编辑 - - - - :

我的问题可能是基于一个新手的错误。是否可以包含一个php文件并同时向其发送数据,以便它在您想要的位置输出数据?喜欢:

<somehtml>
<somejquery> *--> is retrieving Geolocation-coordinates and posting long/lat to "__g.php"*

<?php
    <somephp>
    include("__g.php"); *--> is echoing the full API-url containing the long/lat values from the jQuery-post*
    <someforeach> *--> for the received API-json*
?>
php jquery ajax post echo
1个回答
0
投票

更改以下内容:

   $.post("__g.php", { 
  latitude: latitude, 
  longitude: longitude 
  }).done(function(data) {
     console.log("Data Loaded: " + data);
  });

   $.ajax({
       url: "__g.php",
       type: "POST",
       dataType "text",
       data: {
          latitude: latitude, 
          longitude: longitude
       },
       success: function(data) {
         console.log("Data Loaded: " + data);
       },
       error: function(data) {
          console.log("Error: an error occurred somewhere");
       } 
  });

更改您的PHP代码:

$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
echo "Position output: " . $latitude . $longitude;

if (isset($_REQUEST['latitude']) && isset($_REQUEST['longitude'])) {
   $latitude = $_REQUEST['latitude'];
   $longitude = $_REQUEST['longitude'];

   print "Position output: " . $latitude . $longitude;
} else {
    header('HTTP/1.1 500 Internal Server');
    header('Content-Type: application/json; charset=UTF-8');
}
© www.soinside.com 2019 - 2024. All rights reserved.