我有以下API: api_get.products.php
,它应该从all the products
给我database
。
当on the front-end
和我parse the result
,并且我尝试access the array´s object´s key properties
one by one
时,它为所有属性提供了undefined
。
我想补充说same solution
在data came from a text file
时工作正常。那么当data comes from MySQL
有different way to access
时呢?
echo
的{{1}},但回声是正确的。
$sjResponse
出了什么问题?
[{"productCode":"200","productName":"B","productDescription":null,"quantityInStock":"198","buyPrice":"2.00","image":"img/product-image.1.png"},{"productCode":"1000","productName":"A","productDescription":null,"quantityInStock":"233","buyPrice":"1.00","image":"img/product-image.2.png"}]
这是ajax,其中一切都应该没问题,我只是解析响应。
<?php
try {
// connect to the database
require 'connect.php';
// create a query
$query = $conn->prepare("SELECT * FROM products");
// run the query
$bResult = $query->execute(); // result of this will return true or false
$sajResult = json_encode( $query->fetchAll(PDO::FETCH_ASSOC) ); //fetch the result and turn it into a string
//echo $sajResult;
$sjResponse = $bResult ? $sajResult : '{"status":"error"}'; // means if the query is true or false
echo $sjResponse;
} catch (Exception $e) {
echo "ERROR";
}
?>
这是我尝试访问function getajProductData() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if ( this.readyState == 4 && this.status == 200 ) {
ajProductDataFromServer = JSON.parse( this.responseText );
console.log( "Response:" + ajProductDataFromServer );
if ( sessionStorage.getItem('role') === "admin" ) {
//console.log( "PRODUCTS ARE EDITABLE" );
showProductAdmin();
} else if ( sessionStorage.getItem('role') === "user" ) {
//console.log( "PRODUCTS ARE AVAILABLE FOR USER" );
showProduct();
} else {
//console.log( "PRODUCTS AVAILABLE FOR PUBLIC" );
showProduct();
}
}
}
request.open( "GET", "api_get_products.php", true );
request.send();
}
的地方。这也是array´s object´s properties one by one
之前的worked fine
。
data came from a text file
答案 0 :(得分:0)
// DISPLAY PRODUCTS for USER / PUBLIC dinamically using a loop and then INSERT into HTML
function showProduct() {
lblProductList.innerHTML = "";
for ( var i = 0; i < ajProductDataFromServer.length; i++ ) {
var lblProduct = '<div class ="lblProduct">' + '<a href="#' + ajProductDataFromServer[i].image + '">' + '<img src="' + ajProductDataFromServer[i].image + '" width="85%" class="lblProductImage" alt="product">' + '</a>' + '<a href="#_" class="lightbox" id="' + ajProductDataFromServer[i].image + '">' + '<img src="' + ajProductDataFromServer[i].image + '">' + '</a>' + '<h3 class ="lblProductName">' + ajProductDataFromServer[i].productName + '</h3>' + '<h3 class ="lblProductPrice">' + 'Price:' + ' ' + ajProductDataFromServer[i].buyPrice + '<h3 class ="lblProductQuantity">' + 'Quantity:' + ' ' + ajProductDataFromServer[i].quantityInStock + '</h3>' + '<button class="btnBuyProduct" data-productId="' + ajProductDataFromServer[i].productCode + '" >' + 'BUY PRODUCT' + '</button>' + '</div>';
lblProductList.insertAdjacentHTML( 'beforeend', lblProduct );
}
}