将Json从PHP发送到JS

时间:2018-02-02 23:43:28

标签: javascript php jquery json ajax

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

的Javascript

conn.setRequestProperty("Cookie",cookie);

PHP,product.php 代码:

$(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,输出功能:

<?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);
}
?>

Home.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?
}

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

我为这个问题道歉,但我很绝望! :(

1 个答案:

答案 0 :(得分:2)

在你的js文件中:

order by id