jQuery(不带$ .ajax)$ .POST + json从PHP json_encode中检索“null”

时间:2012-09-07 12:07:14

标签: php jquery ajax json

我第一次写作,但不是第一次写作。我觉得我不得不在这里问一下,因为这里没有一个明显相似的问题能给我一个明确的解决方法或解决方案。 我的项目涉及一个tic-tac-toe游戏,所有jQuery,PHP和基于日志文件。它运行正常,但是对于发送到txt日志的每个信息,我必须为一个新的$ .post加注星标以检索将在页面的不同部分显示的信息,而不是全部在一个列表中(特别是O和X被检索回原始文本元素)... 游戏是实时的,多人游戏并且工作正常,但是使用由PHP编写的两个txt日志来管理游戏:一个日志保持位置(填充空间),另一个使用char(X或O)。很好,但是我通过$ .post调用两个,将它们的数据存储在各自的全局变量中并在setInterval中使用它们,以便及时更新其他玩家。但是由于还有许多其他信息,如名称和剩余移动(从9到1),我想将所有内容放在一个日志中,更容易一次性检索,并通过游戏显示在各自的位置页。我的问题(现在我需要立即工作)这里是从PHP中检索它们。在测试期间,我模拟三个信息:position,char(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
?>

两者都是帖子,都使用json,jQuery返回一些东西,但是为空,PHP回声没问题...... $ .ajax根本就没有成功... 我需要的是:$ .post检索每个数据,以便我可以逐个存储在它们各自的全局变量中,但是如果警报甚至无法显示其中一个来,那就错了。更改了每个变量名称以避免任何类型的冲突,而不是解决... 我做了这个测试只是为了确保jQuery清楚地得到PHP json,这里没有发生什么。我的HTML使用默认字符集,我在localhost中测试它,我的主要项目在这里工作得很好,这是一个侧面测试,专门测试json响应。我只是没有成功使用$ .ajax({})(我的jQuery是1.7.1),无论如何,脚本只是停止执行,PHP在这里保持响应,但是jQuery并没有给我除了它应该是什么“null”,我在FF15和IE8上测试过它,问题就在于我在jQuery上的json例程,PHP工作正常,我的$ .posts在这里和主项目上也是如此。这可能会出错?为什么它只是将数据返回为null而不管我可能尝试什么?我提前感谢大家,我只是问,因为这里和外面没有任何例子给我答案,99.9%依赖于Ajax,但我相信它可以更简单。

2 个答案:

答案 0 :(得分:1)

将此添加到您的代码中

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

答案 1 :(得分:0)

有效JSON如下:{"key":"value"}而非{key:"value"}

注意:所有引用都是封装的,而不仅仅是值。希望有所帮助。