function categories_get() {
$this->load->database();
$sql = 'SELECT genre AS Genre, COUNT(*) AS Records FROM games ';
$sql .= 'GROUP BY genre;' ;
$query = $this->db->query($sql);
$data = $query->result();
$this->response(json_encode($data),200);
}
我有一个 MySQL 数据库,其中存储了游戏以及游戏的类型。
我使用 APIGEE 控制台运行并测试了上述 PHP 函数,并且它正在输出 JSON 数据。
http://creative.coventry.ac.uk/~4089797/Games/V1.0/index.php/games/categories
我尝试了几种不同的方法,但我不知道如何将此数据动态输出到 JQM 中的 ListView 。
<li><a href="#resultspage1" data-transition="slideup" onclick="Get()">Get Games All Categories</a></li>
它的名字是这样的:
function Get(){
$.ajax({
url: 'http://creative.coventry.ac.uk/~4089797/Games/V1.0/index.php/games/categories',
dataType: 'json',
success: function(data) {
我被困住的地方就在这里。这是我尝试过的,但没有成功。
$('#output1').append('<li><a href="" data-transition="slideup"
onclick="Getgames('+genre+')">'+genre+'
<div class="ui-li-count">'+genre.records+'</div>
</a><li>'
);
我知道自己做错了,但不知道错在哪里。
从中获取数据的表称为games
,并具有id、title、ean、genre、developer
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
}
});
}
这就是我到目前为止所使用的功能,但我不确定使用什么来获取数据以显示到此 ListView
<ul id="output1" data-role="listview"> </ul>
最佳答案
您的代码:
$('#output1').append('<li><a href="" data-transition="slideup"
onclick="Getgames('+genre+')">'+genre+'
<div class="ui-li-count">'+genre.records+'</div>
</a><li>'
);
有一个缺陷。您不能只在字符串中插入换行符,并期望它继续。您必须放置一个反斜杠来指示换行符实际上是字符串的一部分(因此反斜杠后面没有空格!)。
$('#output1').append('<li><a href="" data-transition="slideup" \
onclick="Getgames('+genre+')">'+genre+'\
<div class="ui-li-count">'+genre.records+'</div>\
</a><li>'
);
好多了。
您也没有循环访问收到的 JSON 数据,该数据被假定为包含“流派”和“记录”作为成员的对象数组(区分大小写!)。我为您解决了这个问题,并向按钮添加了 jQuery 单击触发器,而不是“onclick”属性。
$(document).ready(function() {
// get button, get game categories
$("#getbutton").click(function() {
$.ajax({
// make sure this URL is local to your server!
// otherwise browsers may prevent this since it may be dangerous to load external sources
url: 'http://creative.coventry.ac.uk/~4089797/Games/V1.0/index.php/games/categories',
dataType: 'json',
success: function(data) {
// loop through data array elements
for(var i in data) {
// for each, append to the list
$('#output1').append('<li><a href="" data-transition="slideup"\
onclick="Getgames('+data[i].Genre+')">'+data[i].Genre+'\
<div class="ui-li-count">'+data[i].Records+'</div>\
</a><li>'
);
}
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
}
});
});
});
您必须对 HTML 进行的唯一更改是将 id="getbutton"
添加到按钮,如下所示(并删除 onclick
属性):
<li><a id="getbutton" href="#resultspage1" data-transition="slideup">Get Games All Categories</a></li>
关于php - ajax get方法与mysql数据库一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21081257/