【问题标题】:Ajax call not displaying response on successAjax 调用在成功时不显示响应
【发布时间】:2020-11-16 13:59:14
【问题描述】:

我正在尝试在引导模式中显示名为 prints 的 mysqli 数据库表中的相关图像和信息,然后在模式中显示图像、标题等... ajax 调用正在工作并加载响应的 div应该去,但其余的响应都没有填充模态?

我的代码如下:

数据库连接php:`

     <?php
     $dbhost = '*';
     $dbuser = '*';
     $dbpass = '*';
     $dbname = '*';
     $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

     if(! $conn ) {
        die('Could not connect: ' . mysqli_error());
     }
     //echo 'Connected successfully';

  ?>

这会正确连接并在需要时调用

我的主页,其中数据库用于显示相关表格中的缩略图,然后单击并使用模式弹出如下:

<?php include 'CreateDb.php';
ini_set('display_errors', 'on');
error_reporting(E_ALL);
$SQLprintsall = 'SELECT * FROM prints';
$printsall = mysqli_query($conn, $SQLprintsall);

?>
<div id ="shop-header">
  <div id="cont-cart">
  <p>BUY PRINTS</p>
  <ul class="cart-actn">
    <li><a class="fa fa-pound-sign" href="#"></a></li>
    <li><a class="fa fa-shopping-cart" href="#"></a></li>
  </ul>
</div>
<ul class="shop-filters">
  <li class="filter-item">All</li>
  <li class="filter-item"><a href="#">Landscapes</a></li>
  <li class="filter-item"><a href="#">Animals</a></li>
  <li class="filter-item"><a href="#">Europe</a></li>
  <li class="filter-item"><a href="#">Scotland</a></li>
  <li class="filter-item"><a href="#">England</a></li>
  <li class="filter-item"><a href="#">Asia</a></li>
  <li class="filter-item"><a href="#">Canada</a></li>
</ul>
</div>
<!--thumbnail images Loop-->
<div id="shop-thumbs">
<?php while($prints = mysqli_fetch_array($printsall)) : ?>
<div id="image-shop" class="image-holder">
  <button type="button" data-id="<?php echo $prints['image']; ?>" class="img-btn btn-success 
printinfo" >
  <img src="<?=$prints['image_href']; ?>">
  </button>
</div>
<?php endwhile; ?>
<!-- Modal -->
<div class="modal fade" id="empModal" role="dialog">
<div class="modal-dialog">

 <!-- Modal content-->
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
  </div>
  <div class="modal-body">

  </div>
  <div class="modal-footer">
   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  </div>
 </div>
</div>
</div>
<script>

$(document).on('click', '.printinfo', function(){

 var printinfo = $(this).attr('data-id');
 alert("'.$printinfo.'");

 // AJAX request
 $.ajax({
  url: 'wp-content/themes/LEP/Modals/landscape-product-1.php',
  type: 'post',
  data: {printinfo: printinfo},
  success: function(response){
    console.log(printinfo);
    alert(response);
    // Add response in Modal body
    $('.modal-body').html(response);

    // Display Modal
    $('#empModal').modal('toggle');
  }
});
});

</script>

</div> <!-- end of containder from header.php -->

这然后调用模态弹出如下

<?php
include "CreateDb.php";

$printinfo = 0;
if(isset($_POST['printinfo'])){
$printinfo = mysqli_real_escape_string($conn,$_POST['printinfo']);
}
$sql = "SELECT * FROM prints WHERE id =" .$printinfo;
$result = mysqli_query($conn,$sql);

$response = "<div class='modal-holder'>";

while( $prints = mysqli_fetch_array($result)){
$id = $prints['image'];
$image = $prints['image_href'];
$title = $prints['image_title'];

$response .= "<div>";
$response .= "<h1>".$title."</h1>";
$response .= "</div>";

$response .= "<div>";
$response .= "<img src=".$image_href.">";
$response .= "</div>";

}
$response .= "</div>";

echo $response;

?>

点击后一切正常,但除了包含响应数据的 div 之外,模式不加载任何响应?

网站如上http://landscapephotoprints.co.uk

任何帮助将不胜感激

非常感谢

【问题讨论】:

  • 您是否收到警报弹出? alert(response);
  • @GrumpyCrouton 是的两个警报,首先我知道点击正在工作,然后第二个警报显示一个对话框,其中包含应该完全填充响应数据的 div 的 html,对话框框显示 然后阻止额外的对话选项,它不显示任何其他数据
  • 嗨,你能不能简单地alert(printinfo)看看它是否显示正确的数据ID?
  • 您尝试过什么调试问题?这是 PHP 的问题,还是 jQuery 的问题?
  • 这是我试图传递的数据的问题,并且数据库没有连接以查找相关信息,所以更多的是一个 sql 问题,然后我修改了我的方法以使用 json 编码来获取数据以更简单的方式

标签: php jquery ajax


【解决方案1】:

问题是你这样做的方式,“然后调用如下的模态弹出窗口”之后的代码不是这样做的方式。

您永远不应该通过 Ajax 请求获取 HTML 代码/标签。 您应该只获取“纯”数据并将其与 DOM 中的 javascript 集成。

从服务器加载您的 PHP 页面后的理想方式是您的 JS Ajax 查询仅获取非 html 数据作为响应,因此在此示例中,您显示图片的 html 代码应该已经在开始时的 div 中,也许有一张假照片。您的 Ajax 请求应该只接收图片的 url(服务器端的 echo($picUrl))或(甚至更好)多个信息,如 url+title+description+place as JSON(只需在服务器端创建一个 PHP 数组并使用 JSON_ENCODE ($myArray))。


说实话,JSON 可能是您应该能够发送 img url + 各种其他信息以包含在您的模态中的方式。

如果你对这个数组进行编码,它会给你例如{picSrc = "./img/pic043.png", title = "Great pic", date= "2020-11-18"}

$result = [ "picSrc" => "./img/pic043.png", 
            "title" => "Great pic", 
            "date"=> "2020-11-18"];
header('Content-Type: application/json');
echo json_encode($result);

在此处查看详细示例:https://makitweb.com/return-json-response-ajax-using-jquery-php/


简单地说,在您的示例中没有 JSON,您对“wp-content/themes/LEP/Modals/landscape-product-1.php”的 Ajax 请求应该将图片 url 作为响应返回给您(或如果您使用 JSON,则作为响应的一部分)。

此外,您应该已经在模态正文中包含一个虚拟图像:

 <div class="modal-body">
     <img src="./img/nopic.png" id="divImg">
 </div>

所以现在如果你的 Ajax 调用给你图片 url 作为响应,你只需要这样做:

 $.ajax({
  url: 'wp-content/themes/LEP/Modals/landscape-product-1.php',
  type: 'post',
  data: {printinfo: printinfo},
  success: function(response){
 
    $('#divImg').attr('src',response); // Here response would be for exemple "./img/pic043.png"

    // Display Modal
    $('#empModal').modal('toggle');
  }

Boom!,当您点击图库时,您应该会在模态中看到您的图片 :)

【讨论】:

  • 感谢 Velome,使用 json 编码数组当然更有意义,我在以前的版本中确实尝试过,但看看你解释的内容,我认为我没有传递数据作为 JSON 返回可用数组的正确方法,我将在周末实施您的建议,但它肯定看起来朝着正确的方向迈出了一步。再次感谢
【解决方案2】:

我修改了原来的 AJAX 请求,正确地将数据作为 JSON 对象传递,然后在成功函数中使用数据,而不是使用 PHP 来显示响应。根据 Velome 的建议,我沿着 JSON 路线走下去,找到了一个比尝试编辑我的原始 PHP 响应更快的解决方案

$(document).on('click', '.printinfo', function(){

 var printinfo = $(this).attr('data-id');
     imageinfo = $(this).find().closest('img').attr('src');
 alert(printinfo);
 $('.modal-h1').html('');
 // AJAX request
 $.ajax({
  url: 'wp-content/themes/LEP/Modals/landscape-product-1.php',
  type: 'post',
  dataType: 'json',
  data: { printinfo: printinfo},
  success: function(data){
    console.log(data);
    console.log(data[0].href);
    console.log(data[0].id);
    console.log(data[0].title);
    alert(data);
    $('.modal-header').prepend('<h1 class=modal-h1>' + data[0].title +'</h1>');
    $('#modimg').attr('src', data[0].href);

    $('#myModal').modal('toggle');
    // Display Modal
    }
});
});

并更改了while循环选择并设置要返回的数组

 $printinfo = $_POST['printinfo'];

 $sql = "SELECT * FROM prints WHERE image ='".$printinfo."' LIMIT 1";
 $result = mysqli_query($conn, $sql);
 $return_arr = array();

 while($prints = mysqli_fetch_array($result)) : {


  $id = $prints['image'];
  $href = $prints['image_href'];
  $title = $prints['image_title'];

  $return_arr[] = array("id" => $id,
                  "href" => $href,
                  "title" => $title);


} endwhile;

$myJson = json_encode($return_arr);
echo $myJson;
exit;

【讨论】:

    【解决方案3】:

    为了追随 Paul Stephen Davis 的出色工作,我将根据他的响应/代码添加一些最佳实践。

    header('Content-Type: application/json'); // <=== Say "it's JSON data", so for exemple if you go to the url in your browser it's correctly formated/display.
    
    $conn = mysqli_connect("localhost", "my_user", "my_password", "my_db"); // <=== It's not in your code but it's probably here IRL.
    
    if (mysqli_connect_errno()) {  // If there is an error with database connection it will send Json {error: "Failed to connect to MySQL: The error msg here."} with error code 500 (Server Intarnal Error).
      http_response_code(500);
      echo json_encode(["error"  => "Failed to connect to MySQL: " . mysqli_connect_error()]);
      exit();
    }
    
    $printinfo = $_POST['printinfo'];
    
    // Here we gonna use "Prepared Statement" so it's safer if someone is trying to do MySQL injection (aka: trying to insert stuff in the string with the variable to do unatended things).
    $sql = "SELECT * FROM prints WHERE image = ? LIMIT 1"; // Put ? where the variable is.
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $printinfo); // Bind the value to the ?.
    $stmt->execute();
    $result = $stmt->get_result();
    
    if (!$result) {  // If there is an error with query it will send Json {error: "Error with MySQL Query: The error msg here."} with error code 500 (Server Intarnal Error).
      http_response_code(500);
      echo json_encode(["error"  => "Error with MySQL Query: " . mysqli_error($conn)]);
      exit();
    }
    
    $return_arr = array();
    
    while ($prints =  $result->fetch_assoc()) : {
        $id = $prints['image'];
        $href = $prints['image_href'];
        $title = $prints['image_title'];
    
        $return_arr[] = array(
          "id" => $id,
          "href" => $href,
          "title" => $title
        );
      }
    endwhile;
    
    mysqli_close($con); // It will close the database connection (it will still be close at the end of script but its "by principle").
    
    $myJson = json_encode($return_arr);
    
    if($myJson === false || is_null($myJson)){ // <=== We check if JSON encoding want wrong.
      http_response_code(500);
      echo json_encode(["error"  => "Error encoding JSON."]);
      exit();
    }
    echo $myJson;
    exit;
    

    请记住,数据库本机错误消息应仅在开发/调试模式中发送,而不是在生产中发送,因为它会泄露重要信息。

    请记住,这不是做这件事的“好方法”,要做得更好,您可以使用“try catch”并在错误检查中抛出错误,例如:

    if(mysqli_connect_errno()) throw new Exception("连接 MySQL 失败:" .mysqli_connect_error());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 2017-12-08
      • 1970-01-01
      • 2020-03-23
      • 2021-11-30
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      相关资源
      最近更新 更多