【问题标题】:Create special JSON file with jquery AJAX and PHP使用 jquery AJAX 和 PHP 创建特殊的 JSON 文件
【发布时间】:2020-02-26 18:41:03
【问题描述】:

我有以下 json 文件格式:

{       
"Deutsch":"German",
"Englisch":"English",
"Französisch":"French",
"Spanisch":"Spanish",
}

现在我想用 PHP 读取这个文件并在我的网站上的 textareas 中打印它:

$file = '../js/json/en.json';
$json = file_get_contents($file);
$obj = array();
$obj = json_decode($json, true);

$output .= "<table style='width:100%'>";
$output .= "<tr>";
$output .= "<th>German</th>";
$output .= "<th>English</th>";
$output .= "<th>Your Language</th>";
foreach($obj as $key => $val) {
    $output .= "<tr><td><textarea class='german' style='width:100%;' readonly>".$key."</textarea></td><td><textarea class='english' style='width:100%' readonly>".$val."</textarea></td><td><textarea class='new_lang' style='width:100%'></textarea></p></td></tr>";
}
$output .= "</table>";

到目前为止效果很好。

之后,我需要从上面的两个文本区域中读出内容,并将其写入一个新的格式相同的 json 文件中。到目前为止,这是我遇到问题的部分:

$("#save_translation").on("click", function() {

        let obj = {};
        $(".new_lang").each(function() {
            var te = $(this).parents("tr").find(".german").val();
            var tt = $(this).val();
            obj = {...obj, [te]:tt};
        });
        //console.log(obj);

        $.ajax({
           type: "POST",
           url: "/trans.php",
           dataType: "json",
           data: {myData:obj},
           contentType: "application/json; charset=utf-8", // php://input
           success: function(data) {  
                console.log("test: ", data);
            }
        });

    });

还有 trans.php 文件:

$myArray = $_POST['myData'];
$posts = array();
foreach($myArray as $key => $value) {
    //array_push($posts, $key .":". $value);
    $posts[] = array("$key" => "$value");
}
var_dump( $myArray);

$fp = fopen('js/json/tfr.json', 'w');
fwrite($fp, json_encode($posts));
fclose($fp);

有没有人有提示如何正确地获得与上述格式相同的格式??

提前致谢。

【问题讨论】:

  • 输出现在的样子

标签: php jquery arrays json object


【解决方案1】:

你可以改变

$posts[] = array("$key" => "$value");

$posts[$key] = $value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多