javascript - 将 JSON 从 PHP 发送到 JS

标签 javascript php jquery json ajax

我正在向我的服务器请求一些数据。我使用了带有 JSON 对象(其中包含所选对象的 ID)的 AJAX 调用,并且我希望服务器向 AJAX 调用返回一个新的 JSON 对象,其中包含有关具有指定 ID 的产品的所有信息。下面是代码

JavaScript:

$(document).ready(function() {

    // AJAX request on submit (login form)
    $("#form-login").submit(function (e) { // this works
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "submit.php",
            data: {
                Email: document.getElementById('login-email').value, // Email in the form
                Password: document.getElementById('login-password').value // Password in the form
        },
            cache: false,
            success: function() {
                window.location.href = "home.php"; // load the home.php page in the default folder
            }
        });
    });

    function getProduct(ID_product) {
        //AJAX request to get a product data from the server
        $.ajax({
            type: "POST",
            url: "product.php",
            dataType: "json",
            data: {
                 id_product: ID_product // the id of the single product
            },
            // success: function(data){ // here begin problems
            //     var obj = JSON.parse(data);
            //     alert(obj); // debug
            // }
            complete: alert("TEST")
        });
    }
});

PHP,product.php代码:

<?php
require('include/header.php');

#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
    exit("Empty post to product.php");
}

if(!empty($_POST)){
    $id = $_POST['id_product'];

    $query_findProduct =  $db->query("SELECT Name, Description, Price, Available FROM PRODUCTS WHERE ID_product='$id' ");
    $product = $query_findProduct->fetch(PDO::FETCH_ASSOC);
    output($product);
}
?>

PHP,输出函数:

# Function to set JSON output
function output($Return=array()){
    header('Content-Type: application/json; charset=UTF-8');
    #exit(json_encode($Return)); # what's the difference with echo?
    echo json_encode($Return); # what's the difference with exit?
}

Home.php实用程序代码:

<?php
# getting all the product
$query_showProducts =  $db->query("SELECT ID_product, Name, Description, Picture, Price FROM PRODUCTS");

# putting all the products in an array
$products = array(); # an array that will contain all the product in the DB
while($prod = $query_showProducts->fetch(PDO::FETCH_ASSOC)){
    $products[] = $prod; # filling the array
}

#query that will store the total number of products in $productNumTot
$query_countProducts =  $db->query("SELECT COUNT(ID_product) FROM PRODUCTS");
$transitory = $query_countProducts->fetch(PDO::FETCH_ASSOC);
$productNumTot = $transitory['COUNT(ID_product)']; # total number of products

?>

<div id="products_area">
    <div id="categories">
        <ul>
            <li><a href="">Other</a></li>
            <li><a href="">Laptop</a></li>
            <li><a href="">Smartphone</a></li>
        </ul>
    </div>
    <div id="products">

        <?php
        for ($i=0; $i<$productNumTot; $i++){
            ?>
                <div id="product-box" onclick="getProduct(<?= $products[$i]['ID_product'] ?>)">
                    <div id="product-area-image">
                        <div id="product-image">
                            <?php
                                echo '<img src="data:image/png;base64,'.base64_encode( $products[$i]['Picture'] ).'"/>';
                            ?>
                        </div>
                    </div>
                    <div id="product-name">
                        <p><?= $products[$i]['Name'] ?></p>
                    </div>
                    <div id="product-price">
                        <p><?= $products[$i]['Price'] ?></p>
                    </div>
                </div>
            <?php
        }
        ?>

    </div>
</div>

我的问题是:服务器会将 JSON 对象存储在全局变量中以便将其发送回 AJAX 请求吗?客户端如何能够接收并显示从服务器获得的 JSON(我是否需要在 JS 中构建一个带有包含 JSON 响应的参数的函数?)?如果我只是想让我的客户选择这个 JSON 并显示它,我该怎么办?

对于这个问题我深表歉意,但我很绝望!

最佳答案

在你的js文件中:

 function getProduct(ID_product) {
        //AJAX request to get a product data from the server
        $.ajax({
            type: "POST",
            url: "product.php",
            dataType: "json",
            data: {
                 id_product: ID_product // the id of the single product
            },
            success: function(data){ // data is a json object
                  console.log(data);//don't convert it (it's already an object)
            }
        });

关于javascript - 将 JSON 从 PHP 发送到 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48592425/

相关文章:

javascript - 我正在尝试让 jquery 插件在我的 wordpress 网站上工作

javascript 变量返回奇怪的输出

javascript - 如何限制 highstock.js 中导航器的大小?

php - 向 Eloquent 资源添加过滤器以有条件地附加关系

java - 我在这里给出一个 O/P。我需要使用 PHP 和 JAVA 的代码

javascript - jwplayer 从另一个域流式传输 m3u

php - 将 jQuery $.post 返回数据设置为 JavaScript 变量

javascript - jquery 文本区域中的最大字符数

javascript - 使用 Angular Directive(指令)在页面加载时重新缩放和裁剪图像

javascript - 使用 HTML <video> 按顺序无缝播放视频文件