Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过json和jquery发布_Javascript_Php_Jquery_Json - Fatal编程技术网

Javascript 通过json和jquery发布

Javascript 通过json和jquery发布,javascript,php,jquery,json,Javascript,Php,Jquery,Json,我对JSON格式完全陌生,所以这可能是一个非常普通的问题,我甚至不确定这是正确的方法 我想做的是编写一个JSON文件,其中包含一些文本,类似于对话列表 var conversations = [ one [{ "you":"Hello", "him":"Hey there" }], two [{ "you":"Hello on this second one", "him":"Hey there ho

我对JSON格式完全陌生,所以这可能是一个非常普通的问题,我甚至不确定这是正确的方法

我想做的是编写一个JSON文件,其中包含一些文本,类似于对话列表

var conversations = [
    one [{
        "you":"Hello",
        "him":"Hey there"
        }],
    two [{
        "you":"Hello on this second one",
        "him":"Hey there how are you"
    }]
];
然后,在pageload上,在我可以使用jquery的php索引上加载一个随机对话。对我来说,重要的是将you/me内容发送到某些特定的div

用例是:页面加载、随机选择对话并在我的页面上呈现

<div class="you">Hello</div>
<div class="him">Hey there</div>

我的方向是好的吗?有什么建议或资源,我可以研究有这样的工作?任何提示或代码都非常感谢:谢谢,这就是你要找的吗

<div id="you"></div>
<div id="him"></div>

<script>
    var conversations = [
        {
            you:"Hello",
            him:"Hey there"
        },
        {
            you:"Hello on this second one",
            him:"Hey there how are you"
        }
    ];

    // random number from 0 to 1
    var random = Math.floor((Math.random() * 2) );

    var you = document.getElementById('you');
    var him = document.getElementById('him');

    you.innerHTML = conversations[random]['you'];
    him.innerHTML = conversations[random]['him'];
</script>

我同意你的看法。我总是喜欢JSON而不是数据库。特别是像你这样的谈话项目。可读性更强,易于编辑等

这是我保存文本对话的json文件

var conversations = [
    one [{
        "you":"Hello",
        "him":"Hey there"
        }],
    two [{
        "you":"Hello on this second one",
        "him":"Hey there how are you"
    }]
];
messages.json

{
"1442831655": {
    "writtenFrom": "tom",
    "line1": "tom writing to jim."
}
action.php

$fileName = "./data/messages.json";
    $str_data = file_get_contents($fileName);
    $data = json_decode($str_data,true);

    echo json_encode( $data );
index.php

    ...<script src="../public/js/jquery-2.0.3.min.js"></script>
<script src="ad.js"></script>...

我只是想给你一些想法。整个脚本要复杂得多。PHP、AJAX、JSON

您的示例将是一个javascript文件,而不是一个包含JSON的文件。但要存储数据,我建议使用数据库,而不是json/text/javascript文件。您可以在服务器端php和客户端js/jQuery中做您想做的事情。@jeroen谢谢!这其实是一个小项目,我不需要那么复杂的东西。javascript文件更适合吗?你会怎么做?对不起,但是有很多理由来结束这个问题,因为这个问题过于宽泛、基于观点、要求非现场资源。。。。当您遇到特定问题时,应该尝试一下,然后在这里发帖。从数据库中存储和检索比编写动态文件要简单