我想知道如何使用jquery / Ajax从PHP文件中获取PHP数组字段值。事实上,我有三个文件:mapage.html,moslem.php和moslem1.php。您可以在下面找到每个文件的代码。
mapage.html的代码:
<script type="text/javascript">
$(document).ready(function() {
setTimeout( test, 1000);
});
function test() {
$.ajax({
url: 'moslem.php',
type: 'POST',
success: function(data) {
var max;
max = data;
setTimeout( test1, 500);
function test1() {
$.ajax({
url: 'moslem1.php',
type: 'POST',
success: function(data1) {
document.write(data1+"<br>");
}
});
}
}
});
setTimeout( test, 1000);
}
moslem.php的代码:
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)) {
$max=$row['Id'];
}
echo $max;
mysqli_close($con);
?>
moslem1.php的代码:
<?php
$con = mysqli_connect("localhost", "root", "", "test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while ($row = mysqli_fetch_array($result)) {
$notification = array('id' => $row['Id'], 'subject' => $row['Subject'], 'location' => $row['Location'], 'description' => $row['Description'], 'starttime' => $row['StartTime'], 'endtime' => $row['EndTime']);
}
print_r($notification);
mysqli_close($con);
?>
好吧,当我运行文件mapage.html时,它每隔一秒显示以下行:
Array ( [id] => 22 [subject] => reading books [location] => at home [description] => reading some books. [starttime] => 2014-05-21 11:00:00 [endtime] => 2014-05-21 12:00:00 )
因此,您可以在上面看到它显示数组的内容&#34; notification&#34;存在于moslem1.php的代码中。现在,我的问题是如何修改下面的行以仅显示该数组的字段值(例如,字段&#34; subject&#34;或任何其他字段的值):
document.write(data1+"<br>");
提前致谢。
答案 0 :(得分:1)
将dataType:'JSON',
添加到您的Ajax请求中,并将print_r($notification);
更改为echo json_encode($notification);
中的moslem1.php
,然后您就可以document.write(data1.subject);