我试图从我的json文件加载php和JQuery ajax获取音乐类型列表。
这是我的json格式
[
"12-bar blues",
"2 tone",
"2-step garage",
"4-beat",
"50s progression",
"a cappella",
"accordion",
"acid breaks",
"acid house",
"acid jazz",
"acid rock",
"acid techno",
"acid trance",
"acousmatic music",
"acoustic"
]
JQuery的的
// Get genres
$("#showgenres").click(function(){
var genres = $("#genrelist");
$.ajax({
url: base_url + "genres/index",
method : "GET",
success: function(data){
genres.append(data);
}
});
return false;
});
PHP
public function index(){
$file = include APPPATH . "third_party/genres-master/genres.json";
echo $file;
//echo json_encode($file);
}
我的HTML文件
<h3>Genres:</h3>
<hr>
<div id="genrelist"></div>
<button id="showgenres">Show</button>
我只是获得“原始”json输出,我想从数组获得类型值?
答案 0 :(得分:0)
修复从服务器返回json的方式:
public function index(){
$file = file_get_contents(APPPATH . "third_party/genres-master/genres.json");
header('Content-Type: application/json');
echo $file;
}
您需要创建要追加的html元素。
// Get genres
$("#showgenres").click(function(){
var genres = $("#genrelist");
$.ajax({
url: base_url + "genres/index",
method : "GET",
success: function(data){
var html = "<ul>"
for(var i = 0; i < data.length; i++) {
html += ("<li>"+data[i]+"</li>");
}
html += "</ul>";
genres.append(html);
}
});
return false;
});
替换Ajax调用(我在这里托管了json http://myjson.com/hs8kd):
// Get genres
$("#showgenres").click(function(){
var genres = $("#genrelist");
$.ajax({
url: "https://api.myjson.com/bins/hs8kd",
method : "GET",
success: function(data){
var html = "<ul>"
for(var i = 0; i < data.length; i++) {
html += ("<li>"+data[i]+"</li>");
}
html += "</ul>";
genres.append(html);
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Genres:</h3>
<hr>
<div id="genrelist"></div>
<button id="showgenres">Show</button>
答案 1 :(得分:0)
var htmlData = "";
$.ajax({
url: base_url + "genres/index",
method : "GET",
success: function(data){
data=JSON.parse(data);
$.each(data,function(i,v) {
htmlData+=v+"<br/>";
}
genres.append(htmlData);
}
});
这将显示数据:
12条布鲁斯
2音
2步车库
4拍
50s进展
无伴奏合唱
手风琴
酸中断
酸房子酸爵士
酸性岩石
酸技术
酸性恍惚
acousmatic music
声
答案 2 :(得分:-1)
您可以使用以下
$.ajax({
dataType: "json",
url: base_url + "genres/index",
method : "GET",
success: function(data){
genres.append(data);
}
});