首页 > 解决方案 > 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 文件正确解码和编码,但键的值仍然不会改变。

标签: javascriptphpjqueryjsonajax

解决方案


您在 php if 语句中分配值:

if($data[0]['answear05count'] = $count){
  $data[0]['answear05count'] = $count+1;
}

应替换为:

if($data[0]['answear05count'] == $count){
  $data[0]['answear05count'] = $count+1;
}

对所有其他 if 语句执行相同操作


推荐阅读