我正在尝试通过ajax从我的数据库中检索数据,console.log显示我想要的所有结果,但是在我的html中它只显示一个结果,这是最后一个数据。为什么是这样?有人可以帮助我吗?
我很容易回答,因为我是新手:)
<div class="mI">
<section>
<div class="pM" id="m1"></div>
</form>
</section>
<aside class="mBI">
<div class="mT">
<p id="m2"></p>
</div>
<p id="mG"></p>
<p style="margin-top:-8px" id="m3"></p>
</aside>
</div>
$(document).ready(function() {
"use strict";
function connect2mO() {
$.ajax({
url: "tes.php",
type: "GET",
//data:"",
dataType: "json",
//async:false,
success: function(data) {
$.each(data, function() {
var mP = this.p;
var mT = this.t;
var mG = this.g;
console.log(mP);
console.log(mT);
console.log(mG);
$('#m1').html('<img src="p/' + mP + '"/>');
$('#m2').html(mT);
$('#m3').html(mG);
});
},
error: function connect2mO() {
alert('error loading mO');
}
});
}
if (window.attachEvent) {
window.attachEvent('onload', connect2mO);
} else if (window.addEventListener) {
window.addEventListener('load', connect2mO, false);
} else {
document.addEventListener('load', connect2mO, false);
}
});
<?php
include ('session_start.php');
include ('db_connect_mO.php');
$sql = mysqli_query($con, "SELECT * FROM mo ORDER BY mRD");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'p'=> $row['mP'],
't'=> $row['mT'],
'g'=> $row['mG'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
以下代码将在php中输出我正在尝试使用ajax实现的内容。
<?php while ($row = mysqli_fetch_assoc($sql)) { ?>
<div class="mI">
<section>
<div class="pM"><img src="p/<?php echo $row["mP"];?>" alt=""/></div>
</section>
<aside class="mBI">
<div class="mT">
<p><?php echo $row["mT"];?></p>
</div>
<p id="mG"></p>
<p style="margin-top:-8px"><?php echo $row["mG"];?></p>
</aside>
</div>
<?php } ?>
答案 0 :(得分:3)
var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];
$.each(data, function() {
$.each(this, function(key,value) {
var display = '<div>'+ key +' = ' +value+ ' </div>';
$('body').append(display);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
对于您的代码,您可以这样做
var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];
$.each(data, function() {
var html = '<hr>'+
'<div class="mI">'+
'<section>'+
'<div class="pM" >' + this.p + '</div>'+
'</form>'+
'</section>'+
'<aside class="mBI">'+
'<div class="mT">'+
'<p>' + this.t + '</p>'+
'</div>'+
'<p></p>'+
'<p style="margin-top:-8px" id="m3">' + this.g + '</p>'+
'</aside>'+
'</div>';
$('body').append(html);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
替换它:
$('#m1').html('<img src="p/' + mP + '"/>');
$('#m2').html(mT);
$('#m3').html(mG);
只会覆盖附加的值:
$('#m1').html($('#m1').html() + '<img src="p/' + mP + '"/>');
$('#m2').html($('#m2').html() + mT);
$('#m3').html($('#m3').html() + mG);