javascript - Traying 用 AJAX 和 PHP 替换 JSON 中的数据
问题描述
我尝试使用 PHP 和 AJAX 和 JavaScript 替换 JSON 中的键值以显示值。
我应该更改的 JSON 数据库:
"answer01count": "1",
"answer02count": "2",
"answer03count": "3",
"answer04count": "5",
"answer05count": "10"
我的阿贾克斯代码:
ans = $("input[name=answear]:checked").val();
$("#result").click(function(){
$("progress").show();
var x = json.Endokrynologia[val];
if(ans==x.answear01){
count = x.answear01count;
}
if(ans==x.answer02){
count = x.answer02count;
}
if(ans==x.answer03){
count = x.answer03count;
}
if(ans==x.answer04){
count = x.answer04count;
}
if(ans==x.answer05){
count = x.answer05count;
}
post_data = { $choice : count };
$.ajax({
method: 'post',
data: post_data,
url: 'count.php',
success: function (data) {
result = data;
alert(result)
}
});
});
php代码:
<?php
$count = $_POST['$choice'];
$jsonString = file_get_contents('question.json');
$data = json_decode($jsonString, true);
if($data[0]['answer01count'] == $count){
$data[0]['answer01count'] = $count+1;
}
if($data[0]['answer02count'] == $count){
$data[0]['answer02count'] = $count+1;
}
if($data[0]['answer03count'] == $count){
$data[0]['answer03count'] = $count+1;
}
if($data[0]['answer04count'] == $count){
$data[0]['answer04count'] = $count+1;
}
if($data[0]['answer05count'] == $count){
$data[0]['answer05count'] = $count+1;
}
$newJsonString = json_encode($data);
file_put_contents('question.json', $newJsonString);
?>
知道我做错了什么吗?!我没有任何错误,但我也没有预期的输出。
更新:更改=为==
我的 json 文件正确解码和编码,但键的值仍然不会改变。
解决方案
您在 php if 语句中分配值:
if($data[0]['answear05count'] = $count){
$data[0]['answear05count'] = $count+1;
}
应替换为:
if($data[0]['answear05count'] == $count){
$data[0]['answear05count'] = $count+1;
}
对所有其他 if 语句执行相同操作
推荐阅读
- c# - C# 我需要一种更有效的方法来检查多个复选框中的值以更改布尔值
- json - JSON 响应格式奇数
- reactjs - 由于未连接表单而取消表单提交 - 控制台错误
- java - cf2016 上的 cfcollection/org.apache.poi 错误,带有一些 .ppsx 文件
- django - 将对象转换为查询集
- python - 如何在 Python 中正确地将非常小的数字从字符串转换为浮点数?
- signal-processing - 将收敛标准转换为 L1 范数
- java - 如何将多个 log4j xml 文件添加到单个项目
- php - 如何在 Laravel 中批量更新多对多相关表?
- linux - sqoop 导入中的 -bindir 参数始终作为 Unrecognized 参数给出:–bindir