Javascript 从JSON API调用获取业务类型列表。并将它们包含在选择菜单中
修订本:Javascript 从JSON API调用获取业务类型列表。并将它们包含在选择菜单中,javascript,php,jquery,json,Javascript,Php,Jquery,Json,修订本: <?php $url = 'http://yoco-core-staging.herokuapp.com/api/common/v1/properties/businessCategories'; $content = file_get_contents($url); $json = json_decode($content, true); ?> <select> <?php foreach($json['data'] as $item) {
<?php
$url = 'http://yoco-core-staging.herokuapp.com/api/common/v1/properties/businessCategories';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
<select>
<?php
foreach($json['data'] as $item) {
print '<option>'.$item[2].'</option>';
}
?>
</select>
这是我输入的新代码,用于获取select语句以显示这些选项。我现在要做的就是创建一个函数来消除重复条目,然后bam就完成了
感谢您提供的所有帮助和评论[请在投票前添加评论] 你可以这样做:
$.ajax({
url: 'http://yoco-core-staging.herokuapp.com/api/common/v1/properties/businessCategories',
dataType: 'JSON',
success: function(data, status) {
//data = JSON.parse(data); this is optional depending on the type you are getting from the server
var len = data.length;
var html = '';
for(var i = 0; i < len; i++){
var id = data[i].Id;
var title = data[i].title;
var group = data[i].group;
html += '<li>'+id+' - '+title+' - '+group+'</li>';
}
$('#somecontainer').html('<ul>'+html+'</ul>');
},
error: function(e) {
console.log(e);
}
});
我不知道字段的名称,但基本上是这样的。你应该试试这个。这将打印返回JSON的所有数据
<?php
$url = 'http://yoco-core-staging.herokuapp.com/api/common/v1/properties/businessCategories';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data'] as $item) {
print $item[0];
print $item[1];
print $item[2];
print '<br>';
}
代码中使用的组引用在JSON对象中没有标识为字段名,因此会出现未定义错误 返回的JSON对象如下所示:
array(2) {
["status"]=>
int(200)
["data"]=>
array(122) {
[0]=>
array(3) {
[0]=>
string(4) "5462"
[1]=>
string(6) "Bakery"
[2]=>
string(27) "Food, drink and hospitality"
}
[1]=>
array(3) {
[0]=>
string(4) "5813"
[1]=>
string(3) "Bar"
[2]=>
string(27) "Food, drink and hospitality"
}
[2]=>
您可以通过使用对象返回的数字引用来循环对象。
对于您的情况,您可以只回显$json[data][1]&$json[data][2]foreach对象。您可以使用PHP您到底需要什么?我认为您对最终结果的期望有点不清楚,您更愿意使用jQuery还是PHP?您尝试过什么吗?更新的问题。如果可能的话,我宁愿使用PHP。我希望用html创建一个选择菜单,食物和饮料是我的选项之一,我需要API调用来动态生成更多选项,因为它们是插入的。在我看来,你刚刚成为全世界最酷的人。。甚至比珍珠酱的那个家伙还要酷。非常感谢你!我没有投反对票,但OP显然使用了由PHP创建的HTML选择。是的,我知道他们也标记了这个jquery+javascript,你已经用一个完全的jquery系统取代了它,它现在使用无序列表覆盖选择,没有解释OP为什么要使用这个方法或它的全部含义。TBH,问题实际上特别提到了“选择菜单”。