Php发送到ajax并且ajax的内部不读取该集合

时间:2017-05-02 21:15:20

标签: javascript php jquery ajax

我想知道如何对视图执行isset可读。

我的代码:

fetch.php

while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
 {
<div class="blog-entry">
  <div class="label__title"><?php echo $row['title'];?></div>
  <div class="label__description"><?php echo $row['text'];?></div>
  <div class="label__time"> <div class="calendar-icon"></div> <?php echo 
   $row['date'];?></div>
   <?php
     if(isset($_SESSION['user'])) {
   ?>
   <a href="php/delete_post.php?id=<?php echo $row['id'] 
   ?>" class="label__delete">Elimina entrada</a>
   <?php
     }
   ?>
 </div>

然后我有一个带有innerhtml的ajax。

ajax.js

var content = document.getElementById("result_para");
 content.innerHTML = content.innerHTML+response;

问题是内部没有打印if(isset ... of php

1 个答案:

答案 0 :(得分:0)

这是AJAX调用

function getInfo() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var content = document.getElementById("result_para");
            content.innerHTML = content.innerHTML + this.responseText;
        }
    };
    xhttp.open("GET", 'results.php', true);
    xhttp.send();
}

我的测试PHP档案results.php

<?php
session_start();
// $_SESSION['user'] = 'julekgwa'; test before setting session
$conn = mysqli_connect("localhost", "root", "000000", "ng_app");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    die();
}
$result = $conn->query('SELECT * FROM `blog`');
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) : ?>
<div class="blog-entry">
    <div class="label__title"><?php echo $row['title']; ?></div>
    <div class="label__description"><?php echo $row['text']; ?></div>
    <div class="label__time">
        <div class="calendar-icon"></div> <?php echo $row['date']; ?></div>
    <?php if (isset($_SESSION['user']))  : ?>
        <!-- this part will only be visible only, if the user $_SESSION['user'] is set -->
        <a href="php/delete_post.php?id=<?php echo $row['id']; ?>" class="label__delete">Elimina entrada</a>
    <?php endif; ?>
    <?php endwhile; ?>
</div>

上述代码的结果。 enter image description here

设置会话$_SESSION['user']后,if (isset($_SESSION['user']))的内容也会发送到AJAX。

$_SESSION['user'] = 'julekgwa'; // after commenting out this line in the results file, the if (isset($_SESSION['user'])) will be executed

这是结果 enter image description here

这部分代码只有在设置$_SESSION['user']时才会执行,您需要在代码前使用session_start();会话的页面上启动会话。

<?php
if (isset($_SESSION['user'])) {
    ?>
    <a href="php/delete_post.php?id=<?php echo $row['id']
    ?>" class="label__delete">Elimina entrada</a>
    <?php
}
?>