【问题标题】:jQuery to PHP $.post not echoing anything on page but echoing data to jQuery [duplicate]jQuery to PHP $.post 不在页面上回显任何内容,而是将数据回显到 jQuery [重复]
【发布时间】:2018-09-11 13:44:46
【问题描述】:

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

【问题讨论】:

  • 在控制台的网络选项卡下检查XHR,是否发送数据
  • @ToE 好的,但您说 但是在页面本身上,PHP-echo 只是回显引号内的内容,而不是变量内容。 您是否正在尝试直接用php脚本运行页面?
  • 这似乎一直出现在 StackOverflow 上。您不能只导航到 PHP 页面;这将是一个GET 请求,它不会有任何$_POST 参数
  • 我不认为你需要 ajax 来实现你最终想要实现的目标。一个简单的表格应该可以解决问题。使用 ajax 以便您可以在发出 ajax 请求的页面上显示数据

标签: php jquery ajax post echo


【解决方案1】:

更改以下内容:

   $.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');
}

【讨论】:

  • @ToE ,您必须先加载 JQuery 库。
  • 您好,感谢您的帖子!不幸的是它返回 {"message":"ERROR","code":"someerror"}
  • @ToE 表示帖子没有设置,尝试为两个变量设置一个测试值,看看是否返回成功
  • 不幸的是,测试值也不起作用。返回到 jQuery/console 的错误数据显示为 [Object Object]。
  • @ToE 我已经更新了我的答案,应该可以解决错误
猜你喜欢
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 2016-12-11
相关资源
最近更新 更多