使用 php 数组进行选择后如何显示图像?

How do I display an image after you've made your selection with a php Array?

我的问题是,解决此问题的最佳方法是什么?

<?
if (in_array("1434", $category)) {
  if($item > 0) {
    $wc_product = wc_get_product($item);
    echo '<img src="' . get_the_post_thumbnail_url($item, 'medium') . '">'; 
  }
}
?>

[1]:

您将使用的一般方法是

  • 有人点击调用 javascript 函数的产品
  • 您的 javascript 对后端 PHP 脚本进行 ajax 调用
  • 您的 php 脚本获取数据并将其作为 JSON 编码字符串回显
  • 您的 javascript 获取此新数据,解析为 JSON 并使图像出现

使用 php,您可以构建初始 html 页面。假设您有一个图像元素来显示所选图像,例如:

<img id='mainImg' src='/placeholder-image.jpg' />

使用产品 ID 之类的东西作为从按钮调用的函数的参数

<button onclick='getProductData(1234)'>View Product</button>

你的 JS 函数看起来像这样

function getProductData(id) {
   let url = '/myBackendPHPendpoint.php?pid=' + id
   $.ajax({url: url,
        success: function(json){
          json = JSON.decode(json)
          $('#mainImg').attr('src', json.image)
        }
    })
}

您的 PHP 页面 myBackendPHPendpoint.php 看起来像

<?php
  $id = $_GET['pid'];
  // database query to get the product data
  // get the result as an object or array in php  
  echo json_encode($result);
?>