使用jQcloud的词云不会出现

时间:2017-03-14 08:50:13

标签: javascript php jquery json word-cloud

我正试图为我的json创建一个词云。我一直在指的是如何使用jQcloud进行文字云的http://mistic100.github.io/jQCloud/demo.html

起初没有任何错误,但现在控制台上出现错误,说它无法创建属性' weight' on string' {text:" mark",weight:8}'。我还是个新手。如果有人可以指出错误,那将是很好的。编码在我的process.php文件中。

if(isset($_POST['submit'])){
    $data = $_POST["d2"];
    $obj = json_decode($data, TRUE);

    $item = array();
    foreach($obj as $key => $value) 
    {
        $item[] = '{text: "'.$key.'", weight: '.$value.'}';

        $sql = "SELECT word FROM test WHERE word = '$key'";
        $r = mysql_query($sql) or die("Error: " . mysql_error());
        $row0 = mysql_num_rows($r);

        if($row0 != 0)
        {
            $found = "UPDATE test SET weight = $value WHERE word = '$key'";
            mysql_query($found) or die ("Error: " . mysql_error());
        }
    }
    echo print_r($item);
}?>

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="jqcloud.css" />
<script type="text/javascript" src="jqcloud-1.0.4.js"></script>
<script type="text/javascript">

var varNameSpace = <?php echo json_encode($item); ?>;
varNameSpace = JSON.parse(JSON.stringify(varNameSpace));
alert(varNameSpace);
$(function() {
    $("#d").jQCloud(varNameSpace);
  });

</head>
<body>
<div id="d" style="width: 550px; height: 350px; border: 1px solid #ccc;"></div>
</body>
</html>

当我提醒 varNameSpace 时,示例输出将如下所示:

{text: "mark", weight: 8},
{text: "zuckerberg", weight: 4},
{text: "money", weight: 2},
{text: "man", weight: 2},
{text: "and", weight: 7},
{text: "having", weight: 1},
{text: "apart", weight: 8},
{text: "rich", weight: 2},
{text: "of", weight: 3},
{text: "world", weight: 2},
{text: "less", weight: 1}

这是控制台上 echo json_encode($ item)的示例输出:

["{text: \"mark\", size: 8}",
"{text: \"apart\", size: 8}",
"{text: \"and\", size: 7}",
"{text: \"zuckerberg\", size: 4}" ...and many more];

当我使用 print_r 回显 $ item 时,这是示例输出:

Array ( [0] => {text: "mark", size: 8} [1] 
=> {text: "apart", weight: 8} [2] 
=> {text: "and", weight: 7} [3] 
=> {text: "zuckerberg", size: 4} ...and many more ) 1

1 个答案:

答案 0 :(得分:0)

您正在为您的变量输出纯JSON格式的字符串。用JSON.parse()换行将其转换为对象:

var varNameSpace = <?php echo json_encode($item); ?>;
varNameSpace = JSON.parse(varNameSpace);