0
我试图更新json文件中某个对象的值。问题是在同一个json文件中有几个同名键值对的兄弟姐妹。如何使用PHP更新JSON文件中的值
我的Json文件看起来像这样:
{"LogIns":[
{"Username":"Alfred",
"password":"123",
"Won":0,"Lost":0},
{"Username":"Farrah",
"password":"123",
"Won":0,"Lost":0}]}
每次有人赢得了手(这是一个纸牌游戏),我需要更新的游戏数量赢或输。
这是AJAX调用PHP文件:
AJAX:
var username = localStorage.getItem("username");
if(document.getElementById(btnId).value == answer){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
console.log("returned:", xhttp.responseText);
}
xhttp.open("POST", "leaderboard.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + username + "&won=1");
}
else{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
console.log(xhttp.responseText);
}
xhttp.open("POST", "leaderboard.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + username + "&lost=1");
}
setTimeout(reloadPage, 2000);
}
你可以把我的话是,HTML是正确的,而不是真正需要的这里,但我的PHP文件看起来像这样:
PHP:
<?php
$username = $_POST['username'];
if(isset($_POST['won'])){
$won = $_POST['won'];
//echo $won;
}
if(isset($_POST['lost'])){
$lost = $_POST['lost'];
//echo $lost;
}
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
foreach($json['LogIns'] as $res){
if($res['Username']==$username){
if(isset($won)){
$add = $res['Won'];
$add = ($add + $won);
$res['Won'] = $add;
echo $res['Won'];
}
else{
$add = $res['Lost'];
$add = ($add + $lost);
$res['Lost'] = $add;
echo $res['Lost'];
}
break;
}
}
file_put_contents('logins.json', json_encode($json));
?>
的xhttp.responseText
被打印在屏幕上总是(“1”),但是当我的print_r $ JSON的赢或输场仍为0
有谁知道我做错了什么?
任何帮助将永远不胜感激。
感谢
为什么使用'突破; '?还没有在if-else语句中看到过。 –
@JeroenBellemans它突破了'foreach'循环 –
是的,做了一些研究,以后可能会有用:)谢谢 –