我对json和ajax完全陌生。我试图从mysql查询中得到一个结果,并用result更新div。我使用不同的片段发现网上,可以得到结果的json编码,但似乎不能做什么呢?
从mysql获取并以json输出的代码或文件名api.php是:
include 'db.php';
$sth = mysqli_query($con,"SELECT * FROM $tableName");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
echo json_encode($rows);
这个输出是这样的
[{"user_id":"320326","type":"BUSINESS","business":"Business name","f_name":"DAVE","l_name":"TEST","email":"test@test.com","token":"","l_number":"0","m_number":"","password":"work","joined":"2018-07-06","sms_opt":"","instant_opt":"","instant_id":"","email_opt":"","offers_opt":"]
加载时要更改的页面上的html为:
<div id="output">this element will be accessed by jquery and this text replaced</div>
加载它并获取信息的代码是:
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var user_id = data[0]; //get id
var f_name = data[2]; //get name
$('#output').html("<b>id: </b>"+user_id+"<b> name: </b>"+f_name); //Set output element html
//recommend reading up on jquery selectors they are awesome
}
});
});
理想情况下,我想测试这一点时,一个按钮被点击,然后使用相应的数据,我不知道我哪里出错,并尝试了一些事情,但很多在线例子太复杂,这是相当基本的外观。提前谢谢。
1条答案
按热度按时间qrjkbowd1#
既然你收到了大量的对象,你就必须迭代它:
所以你的js看起来像这样: