jQuery(没有$.ajax)$.POST+json检索“;空”;来自PHP json_encode


jQuery (without $.ajax) $.POST+json retrieves "null" from PHP json_encode

我第一次写作,但不是第一次。我觉得不得不在这里提问,因为这里那些明显相似的问题都无法给我一个明确的变通方法或解决方案。我的项目涉及一个井字游戏,全部基于jQuery、PHP和日志文件。它运行良好,但对于发送到txt日志的每一条信息,我都必须添加一个新的$.post来检索将显示在页面不同部分的信息,而不是全部显示在一个列表中(特别是O和X,它们被检索回原始文本元素)。。。游戏是实时的,多人游戏,运行良好,但使用了两个由PHP编写的txt日志,PHP也管理游戏:一个日志保持位置(填充空间),另一个日志使用了什么字符(X或O)。很好,但我通过$.post调用这两个,将它们的数据存储在各自的全局变量中,并在setInterval中使用它们,以便为另一个玩家及时更新。但由于还有许多其他信息,如名称和剩余动作(从9到1),我想把所有信息都放在一个日志中,这样可以更容易地一次检索所有信息,并通过游戏页面显示在它们各自的位置。我的问题(现在我需要开始工作)是从PHP中检索它们。在测试过程中,我模拟了三个信息:位置、字符(O或X)和玩家的名字,把它们放在一个数组中,并用json_encode回显它们,如下所示(我的jQuery帖子和我的PHP):

<script type="text/javascript" src="jquery.js"></script>

$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
alert (data); //returns null...
//alert (data.pos); //nothing, script ignores execution
//alert (data[0].pos); //returns null...
//alert (data[1].pos); //returns null...
//alert (data[2].pos); //returns null...
//alert (data[3].pos); //returns null...
//tests above based on some suggestions I'fe found through the web, ineffective...
},"json");

还有我的PHP:

<?php
//Simulating values being received during the game:
$pos='s3'; //simulation player's move on slot 3
$weapon='O'; //player puts O on slot 3
$name= 'fulano';
//Putting general player info into the array to be used by jQuery:
$coord= array();
$coord['pos']= $pos; //Sets the position where the player put his char
$coord['weapon']= $weapon; //The "weapon" to be put in respective "pos"
$coord['nome']=$name; //Player's name to be displayed during the game
echo json_encode($coord); //encoded json is returning {"pos":"s3","weapon":"O","nome":"fulano"} nicely
?>

两者都是post,都使用json,jQuery返回一些东西,但为null,PHP返回正常…$。ajax也没能成功。。。我需要的是:$.post检索每个数据,这样我就可以一个接一个地存储在它们各自的全局变量中,但如果alert甚至不能显示其中一个数据,那就说明有问题了。更改了每个变量的名称以避免任何类型的冲突,但没有解决。。。我做这个测试只是为了确保jQuery可以清楚地获得PHP.json,而这里没有发生什么。我的HTML使用默认的字符集,我在localhost中测试它,我的主项目在这里运行得很好,这是一个测试json响应的附带测试。我只是在使用$.ajax({})时没有成功(我的jQuery是1.7.1),不管怎样,脚本只是停止执行,PHP在这里的响应一直很好,但jQuery除了"null"之外没有给我它应该给的东西,我在FF15和IE8上测试过它,问题只是我在jQuery上的json例程,PHP运行得很好,我在这里和主项目上也发布了$。这里可能出了什么问题?为什么它只是将数据返回为null,而不管我可以尝试什么?我提前感谢大家,我只是问,因为这里和外面没有真正给我答案的例子,99,9%依赖于Ajax,但我相信它可以更简单。

将其添加到您的代码中

$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
     $(data).each(function(){
            alert(this.s3);
            alert(this.0);
            alert(this.fulano);
     });
},"json");

有效的JSON如下:{"key":"value"}不是{key:"value"}

注意:所有报价都经过封装,而不仅仅是价值。希望能有所帮助。