繁体   English   中英

从 PHP 到 JS 的响应在切换到 JQuery 后不起作用

[英]Response from PHP to JS doesn't work after switching to JQuery

所以,我正在开发自己的博客类型的网站,最近在尝试从我的代码中删除 JS 时遇到了一个问题。 所以我有 show.js 和 showpost.php。 这是我在使用 ajax js 时显示博客文章的 JS 代码:

  load: function () {
    posts.ajax({ req: "show" }, function () {
      document.getElementById("cwrap").innerHTML = this.response;
    });
  },

一切正常。 但是当我尝试用 JQuery 版本替换它时

jQuery.ajax({
  type: "GET",
  url: 'app/showpost.php',
  dataType: 'text',

  success: function (data) {
    console.log(data);
    console.log("okokok");
    document.getElementById("cwrap").innerHTML = this.response;           
  }
});

它无法按预期工作。 现在解释我的showpost:php 文件是如何工作的:

<?php
include_once 'config.php';
echo('');
try {
    $stmt = $pdo->prepare("SELECT `name`, `likes`,`imagename`,`comment_id`, `timestamp`, `message` FROM `posts` WHERE `post_id`=? ORDER BY `timestamp` DESC");
   $stmt->execute([$_POST['pid']]);

  } catch (Exception $ex) {
    die($ex->getMessage());
  }

  while ($r = $stmt->fetch(PDO::FETCH_NAMED)) { 
?>
<div id="post" style="box-shadow: 0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important;">
<button id="<?=$r['comment_id']?>" name="like" class="btn" style="  float: right;" action="likepost.php" method="post"><svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24" y="0"/></g><g><g><path d="M13.12,2.06L7.58,7.6C7.21,7.97,7,8.48,7,9.01V19c0,1.1,0.9,2,2,2h9c0.8,0,1.52-0.48,1.84-1.21l3.26-7.61 C23.94,10.2,22.49,8,20.34,8h-5.65l0.95-4.58c0.1-0.5-0.05-1.01-0.41-1.37C14.64,1.47,13.7,1.47,13.12,2.06z M3,21 c1.1,0,2-0.9,2-2v-8c0-1.1-0.9-2-2-2s-2,0.9-2,2v8C1,20.1,1.9,21,3,21z"/></g></g></svg></button>
  <date><?=$r['timestamp']?></date>
  <h4>Bugs: <?=$r['likes']?></h4>
  <h3><?=$r['name']?></h3>
  <div class="message">
    <?=$r['message']?>
  </div>
  <img src="static/<?=$r['imagename']?>"> 
  </div>
 
  <?php }
  $stmt = null;
  $pdo = null;  
?>

如您所见,它是一个 Php 文件,带有一点 html。 当我使用 Xhr 时它运行良好,但现在使用 Jquery 它不起作用! 请帮忙!

编辑: document.getElementById("cwrap").innerHTML = data; 没有任何改变,这可能是我的 showpost.php 没有发送 html 部分的问题。

问题出在您的success(data)回调 function 中。

  document.getElementById("cwrap").innerHTML = this.response;

您正在获取data ,但您正在使用this.response ,这将是未定义的,因为没有定义这样的变量。 ajax 调用中的 dataType 也应该是 html 即dataType: 'html', 所以它应该是这样的:

jQuery.ajax({
  type: "GET",
  url: 'app/showpost.php',
  dataType: 'html',
  
  success: function (data) {
    console.log(data);
    console.log("okokok");
    document.getElementById("cwrap").innerHTML = data;           
  }
});

数据类型需要是 html 或 json

jQuery.ajax({
  type: "GET",
  url: 'app/showpost.php',
  dataType: 'HTML',

  success: function (data) {
    console.log(data);
    console.log("okokok");
    document.getElementById("cwrap").innerHTML = this.response;           
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM