如何在不重新加载页面的情况下获取PHP文件中的javascript数据

时间:2018-08-09 04:09:09

标签: javascript php jquery ajax

我正在尽最大努力创建Twitter克隆,但遇到了一些问题。我希望能够单击帖子,而无需刷新页面,而在页面的叠加层中显示该帖子(就像在Twitter feed上查看回复等一样)。

在script.js中,我检查是否单击并尝试更改URL。

$('body').on("click", ".chirp", function(){
 var uid = $_GET['id'];
 var pid = $(this).attr("id");
 var pidSplit = pid.split("chirp");
 var messageID = pidSplit[1];
 var obj = {foo: "status"};
 $('.chirpOverlay').addClass("active");
 window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});

javascript可以正常工作...但是我很快就会发现,胜利是短暂的。

在profile.php中,我尝试从URL参数获取状态ID。

<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
  $c = $sql->fetch_object();
}
?>

这是行不通的,因为据我了解,使用“ window.history.pushState”仅会更改url-,但不会加载页面。因此,$ _GET语句失败。我需要一种无需单击页面即可刷新进入profile.php的帖子ID的方法。即使这意味着采取其他方法(而不是使用URL参数)。

PS:我也尝试做一个XMLHttpRequest-无济于事。 :(

谢谢!

3 个答案:

答案 0 :(得分:1)

$('body').on("click", ".chirp", function(){
    var uid = $_GET['id'];
    var pid = $(this).attr("id");
    var pidSplit = pid.split("chirp");
    var messageID = pidSplit[1];
    var obj = {foo: "status"};

    $('.chirpOverlay').addClass("active");

    $.ajax({
        url: "profile.php?id="+uid+"&status="+pid,
        type: "GET",
        data: obj,
        dataType: "html",
        success: function(data){
            console.log(data);
        }
    });
 });

答案 1 :(得分:1)

您只需要进行一些工作即可,然后在您发现问题时可以添加更多内容。这应该为您提供一个良好的起点。

这是您的两个文件。确保它们都在同一目录中。

您将需要确保已加载jquery版本。将其放在您要从其调用script.js的任何页面上。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

script.js

$(document).ready(function(){

  $('body').click(function(){

    var id; //define your id.
    var pid;  //define your pid.

    var datastring = 'id=' + uid + '&status=' + pid;
    console.log(datastring);
      $.ajax({

        url: 'profile.php',
        type: 'POST',
        cache: false,
        data: datastring,
        dataType: 'json',
        success: function(data){
          console.log('Made it to the success function: ' + data);
          if (data) {
            //It works, do something.
            console.log(data);

          } else{
            //It does not work, do something.
            console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');

            }

        }

      });    

  });

});

profile.php

<?php

/*
$status_id = $_POST['status'];  //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/

echo 'You made it to your php page.';

?>

几件事:

  • 您不能从js内调用任何php变量。 var uid = $_GET['id'];不起作用。
  • 传递给php页面的任何值都需要进行验证,以确保它是合法值。
  • 您的SQL查询易于进行sql注入。请阅读有关如何参数化查询的内容。 Good Mysqli Practices

答案 2 :(得分:0)

我终于找到了基于AJAX的解决方案。

我创建了一个名为“ chirp_open_ref.php”的新php文件,并将此ajax添加到script.js:

var datastring = 'status=' + messageID;
$.ajax({
    url: "chirp_open_ref.php",
    type: "POST",
    data: datastring,
    cache: false,
    dataType: "text",
    success: function(data){
        $('.chirp-container').html(data);
    }
});

在“ chirp_open_ref.php”内部:

<?php
require 'core.inc.php';

if (isset($_POST['status']) && isset($_SESSION['user_id'])){
  $chirp_id = $_POST['status'];
  $c = "";
  $sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
  if (mysqli_num_rows($sql) > 0){
    $c = $sql->fetch_object();
  }
  include'chirp.inc.php';
}
?>

'chirp.inc.php'只是每个帖子的布局/结构的模板。 这就像一种魅力,但我总是对我如何执行此操作持批评态度。感谢所有帮助人员!