我希望从我的json文件中提取一个变量。我的目标是在php中使用这个变量,以便能够以mysql查询为例。
所以我的json文件在这里:pages/getRank-classic.php?idstart=0
[
{"rank":1,"id":"111","site_name":"test1","site_vip":"No","boost":"0","site_banner":"test.png","site_banner_wallrank":"","site_pointstotaux":"5044","site_motclef1":"Pvp\/Fac","site_motclef2":"Skyblock","site_motclef3":"Cr\u00e9atif","site_motclef4":"Hunger-Games","site_motclef5":"SKywars\/Mini-Gam","site_presentationvideo":"3TGjebmNOfs"},
{"rank":2,"id":"222","site_name":"test2","site_vip":"No","boost":"0","site_banner":"test.jpg","site_banner_wallrank":"","site_pointstotaux":"4114","site_motclef1":"hunger","site_motclef2":"games","site_motclef3":"pvp","site_motclef4":"survival","site_motclef5":null,"site_presentationvideo":"3TGjebmNOfs"}
]
我试图在包含中使用它:
<script type="text/javascript" >
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
alert(test.id);
alert(test.rank);
}
});
</script>
那我该怎么做呢?
答案 0 :(得分:1)
由于它是json数组,因此您还需要指定索引。
test[0].id
您也可以使用这种方式遍历对象,
var data = [{
"rank": 1,
"id": "111",
"site_name": "test1",
"site_vip": "No",
"boost": "0",
"site_banner": "test.png",
"site_banner_wallrank": "",
"site_pointstotaux": "5044",
"site_motclef1": "Pvp/Fac",
"site_motclef2": "Skyblock",
"site_motclef3": "Cr\u00e9atif",
"site_motclef4": "Hunger-Games",
"site_motclef5": "SKywars/Mini-Gam",
"site_presentationvideo": "3TGjebmNOfs"
}, {
"rank": 2,
"id": "222",
"site_name": "test2",
"site_vip": "No",
"boost": "0",
"site_banner": "test.jpg",
"site_banner_wallrank": "",
"site_pointstotaux": "4114",
"site_motclef1": "hunger",
"site_motclef2": "games",
"site_motclef3": "pvp",
"site_motclef4": "survival",
"site_motclef5": null,
"site_presentationvideo": "3TGjebmNOfs"
}];
$(data).each(function () {
alert(this.id);
});
您可以使用ajax获取json,然后在成功事件中,将此代码添加为,
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
$(test).each(function () {
alert(this.id);
});
}
});
答案 1 :(得分:0)
我终于使用了php那样的&gt;
<?php
$jsonlink = '/pages/getRank-classic.php?idstart=0';
$json = file_get_contents($jsonlink);
$link = mysql_connect('localhost', 'database', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('database', $link);
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
mysql_query("UPDATE `database`.`sites` SET `site_rank` = '$value->rank' WHERE `sites`.`site_id` = '$value->id'");
}
mysql_close;
}
?>