我正在尝试学习如何使用jQuery将数据存储在(LAN)服务器上的.json文件中。麻烦的是,代码写了一个空的.json文件,看不到原因。我已经在Stackoverflow中提到了几个答案,并从中得出了我的大部分代码(例如writing JSON object to .json file on server),但没有一个能完全解决我所面临的问题,即处理jQuery包装的.p组中的所有元素。

我有未包含的主要代码,可以正常工作-允许用户添加段落并通过拖动来移动它们。但是,现在我必须将它们写入服务器,以供用户调用并稍后使用。

这是html:

<!DOCTYPE html>
<html>
     <head>
        <link type="text/css" rel="stylesheet" href="todo.css"/>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
        <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

        <script>
            $("document").ready(function() {
                var jsonObject = { "userItem" : [] };
                for ( var index = 0; index < $("p").length; index++) {
                    jsonObject.userItem[index] = $(".p[index]");
                    console.log(index);
                    console.log(jsonObject.userItem[index]);
                };
                // some jQuery to write to file
                $.ajax( {
                    type : "POST",
                    processData : false,
                    url : "json.php",
                    dataType : 'json',
                    data : { json : jsonObject }
                });
            });
        </script>

        <title>To JSON</title>
    </head>
    <body>
        <div id="list">
            <p>Item 1</p>
            <p>Item 2</p>
            <p>Item 3</p>
        </div>
    </body>
</html>


这是PHP:

<?php
$myFile = "general.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_POST["data"];
fwrite($fh, $stringData);
fclose($fh)
?>


我怀疑问题出在这一行:

jsonObject.userItem[index] = $(".p[index]");


我试过了

jsonObject.userItem[index] = JSON.stringify($(".p[index]"));


但这给了我“将循环结构转换为JSON”消息,但我不知道为什么。

我在这里摸索,不胜感激。

谢谢,
罗伊

最佳答案

您无法将DOM元素转换为JSON。

相反,您应该保存HTML源代码。

10-07 19:24
查看更多