我想获取sub-cat div中类别div和子类别数据中的第一类数据。 我正在使用Ajax,Jquery。我试过下面的代码,但结果显示未定义。请告诉我代码错误的地方?
HTML是:
<body class="bg-color">
<div id="page-wrap">
<div class="border-radius">
<div class="box-heading">Assignment</div>
<div class="footer group">
<div id="category">
5
</div>
<div id="sub-cat">
5
</div>
<div id="sub-cat1">
5
</div>
</div>
</div>
</div>
</div>
</body>
Javascript是:
<script type="text/javascript">
$(document).ready(function(){
});
function pageLoad()
{
var result = new Array();
$.ajax({
type: "POST",
url: "get.php",
data: "",
async: false
}).responseText.split(",");
document.getElementById('category').innerHTML = result[0];
}
window.onload = pageLoad;
</script>
PHP代码
<?php
require("_assets/config/dbc.php");
$id = $_REQUEST['id'];
$query = mysql_query("SELECT * FROM category");
while($row = mysql_fetch_array($query)){
$a = '<a href="javascript:void(0);" onClick="vote1(' . $row['cat_id'] . ');">' .$row['title'] . '</a></p>';
}
$query1 = mysql_query("SELECT * FROM subcategory");
while($row1 = mysql_fetch_array($query1)){
$b = '<a href="javascript:void(0);" onClick="vote1(' . $row1['cat_id'] . ');">' .$row1['title'] . '</a></p>';
}
echo $result = $a."*".$b;
?>
实际上我想在页面加载ajax时转到get.php文件并按ID获取类别,按ID获取子类别,按ID获取子子类别。所以我会在我的3个div上显示这些..请理清我的问题..
答案 0 :(得分:1)
你可以通过json在php中使用json_encode
(返回值的JSON表示)来编码值并在ajax中尝试
例如在php
中$sequential = array("foo", "bar", "baz", "blong");
echo json_encode($sequential);
并在ajax成功尝试
success: function(data) {
data = jQuery.parseJSON(data);
}
答案 1 :(得分:0)
我自己完成了。我的代码是:
function vote(id)
{
var result = new Array();
result = $.ajax({
type: "POST",
url: "ajax.php",
data: "work=vote&id="+id,
async: false
}).responseText.split("^");
document.getElementById('sub-cat').innerHTML = result[0];
document.getElementById('sub-cat1').innerHTML = result[1];
//window.location.reload()
}
现在我面临另一个问题..请让我知道如何获得while循环的第一个值。所以我将使用子类别ID获得子子类别。
php代码是:
<?php
require("_assets/config/dbc.php");
if($_REQUEST['work']=="vote")
{
$id = $_REQUEST['id'];
$query = mysql_query("SELECT * FROM subcategory WHERE cat_id='$id'");
$HTML= "";
while($result = mysql_fetch_array($query)){
$HTML .= '<a href="javascript:void(0);" onClick="vote1(' . $result['subcat_id'] . ');">' .$result['title'] . '</a></p>';
}
$HTML .= "^";
$sql = mysql_query("select * from subscategory "HOW TO GET 1ST SUBCATEGORY ID?"") or die(mysql_error());
while($row = mysql_fetch_assoc($sql)){
$HTML .= '<a href="javascript:void(0);" onClick="vote1(' . $row['subcat_id'] . ');">' .$row['title'] . '</a></p>';
}
echo $HTML;
}
?>