我有两个页面,第一个是index3.php,它有一个名为itemAction.php的操作页面,该页面处理来自数据库的查询并返回json_encode的回显
我正在寻找的是如何访问下面返回的JSON数组。我的itemsAction.php返回以下内容:
[{"0":"3","prod_id":"3","1":"red flower","prod_name":"red flower","2":"natural flower","prod_dtl":"natural flower","3":"1500","prod_price":"1500","4":"2","Cateogry_cat_id":"2"},{"0":"4","prod_id":"4","1":"blue flower","prod_name":"blue flower","2":"natural flower","prod_dtl":"natural flower","3":"1500","prod_price":"1500","4":"2","Cateogry_cat_id":"2"},{"0":"5","prod_id":"5","1":"yellow flower","prod_name":"yellow flower","2":"natural flower","prod_dtl":"natural flower","3":"1500","prod_price":"1500","4":"2","Cateogry_cat_id":"2"},{"0":"6","prod_id":"6","1":"white flower","prod_name":"white flower","2":"natural flower","prod_dtl":"natural flower","3":"1500","prod_price":"1500","4":"2","Cateogry_cat_id":"2"}]
这是我的index3.php
<?php
include("dbh.php");
?>
<html>
<head>
<link href="bin/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
//practice onchange
window.onload = function (){
var onChange = document.getElementById("selection");
onChange.addEventListener("change", change);
function change(){
var selectedItemso = document.getElementById("selection");
var catValue= selectedItemso.options[selectedItemso.selectedIndex].value;
var url = "itemsAction.php?cat=" + catValue;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
findoutLoaction(xhr.responseText);
}
}
xhr.send();
}
function findoutLoaction(data) {
var json = JSON.parse(data);
var address = json.myArray[1].prod_name; // Here's the I have an issue
alert(address);
targetLoc.innerHTML = address;
}
}
</script>
</head>
<body>
<div id="comments">
<hr>
<div id="selectOptions">
<select id="selection">
<option value="1">Food</option>
<option value="2">Flowers</option>
<option value="3">Clothes</option>
<option value="4">Toys</option>
<option value="5">Perfoume</option>
</select>
</div>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
您已经有了数据。您应该可以使用for ...以某种方式遍历数组:
for (var key in json) {
console.log("key: " + key);
console.log("array item:" + json[key]);
}
插入此代码而不是您的** .. **行。您可以像使用php中的任何关联数组一样使用数组。
答案 1 :(得分:0)
我认为您的JSON结构错误。
{..}是对象, [..]是数组,
因此在您的json中,[{...},{...},{...},{...}]是由4个没有键的对象组成的数组,可以通过索引来访问。
在每个对象中,您正在正确使用键,但是命名可能是错误的。你有:
{0:“ 3”
1:“红色花朵”
2:“天然花”
3:“ 1500” 4:“ 2”
Cateogry_cat_id:“ 2”
prod_dtl:“天然花”
prod_id:“ 3”
产品名称:“红色花朵”
产品价格:“ 1500”}
左为键,右为值
然后您拥有:json [0] .prod_name为您提供第一个产品名称“ read flower”,依此类推。