weixin_33720452 2018-02-02 23:43 采纳率: 0%
浏览 39

将Json从PHP发送到JS

I'm asking to my server some data. I used an AJAX call with a JSON object (wich contains the ID of the selected object), and I want the server to return back to the AJAX call a new JSON object containing all the information about the product with the specified ID. here below there's the code

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 code:

<?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, output function:

# 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 code for utility:

<?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>

My question is: will the server store the JSON object in a global variable for sending it back to the AJAX request? How can the client be able to recive and display the JSON obtained from the server (have I to build a function in JS with a parametr that will contain the JSON response?)? What I have to do if I simply want my client to pick this JSON and display it?

I apologise for the question, but I'm desperate! :(

  • 写回答

1条回答 默认 最新

  • 北城已荒凉 2018-02-02 23:54
    关注

    in your js file:

     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)
                }
            });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备