2011-01-31 93 views
1

我用ajax这样获得来自服务器的数据获得的数据:(编者)

$(document).ready(function() 
{ 
    setInterval(function() 
    { 
    $.get('/forms/requestProcessor.php', function(data) 
    { 
     $("#shout").append(data.question+'<br>'); 
     alert('Load was performed.'); 
    },'JSON'); 
    }, 5000); // 5 seconds 
}); 

在PHP文件,我发送的数据是这样的:

while($row=mysql_fetch_array($result)) 
{ 
    $question=$row['Question']; 
    $choice1=$row['Choice1']; 
    $choice2=$row['Choice2']; 
    $choice3=$row['Choice3']; 
    $choice4=$row['Choice4']; 

    $return_data->question = $question; 
    $return_data->choice1 = $choice1; 
    $return_data->choice2 = $choice2; 
    $return_data->choice3 = $choice3; 
    $return_data->choice4 = $choice4; 

    echo(json_encode($return_data)); 
} 

它打印“未定义”。但是,如果我将浏览器直接指向php文件,它将以json格式正确显示数据

+0

我做了它的工作使用$ .getJSON函数,而不是使用$不用彷徨()函数......然而,正如我在上面所指出的,如果我使用回声里面的while循环,它不工作...如果我在while循环外使用回声,我将只得到我的查询的最后一行...有人能告诉我如何克服这个问题? – CuriousCoder 2011-01-31 04:44:21

回答

2

是的,这是可能的最简单的方法是返回json_encoded字符串。所以你的代码看起来像这样 PHP:

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 

    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); 

    header("Cache-Control: no-cache, must-revalidate"); 

    header("Pragma: no-cache"); 

    header("Content-type: text/x-json"); 

    echo json_encode($array); 

    exit(0); 

和JavaScript是这样的:

$.get('/forms/requestProcessor.php', function(data) 
{ 
    .... 
}, 'json'); 
1

它看起来好像您正在接收结果字符串,其中没有真正的结构。

如果你愿意,你可以在你的编码任何数据你是想发回的JSON形式使用json_encode(),并改变你的$.get()请求期待JSON的设置,这样你可以简单地通过data.choice2等访问它们..

例如

$return_data->question = $question; 
$return_data->choice1 = $choice1; 
$return_data->choice2 = $choice2; 
... 
$return_data->choice5 = $choice5; 

echo json_encode($return_data); 

,然后你$.get()

$(document).ready(function() 
{ 
    setInterval(function() 
    { 
    $.get('/forms/requestProcessor.php', function(data) 
    { 
     $("#shout").append(data+'<br>'); 
     alert('Load was performed.'); 
    },'json');    //<-- added, last argument to expect 'json' 
    }, 5000); // 5 seconds 
}); 

现在数据将以json格式返回,并且将由jQuery解析,因为它预计它是json。

所以,你可以现在语句访问数据在你的成功之类的函数data.questiondata.choice1等..

+0

嗨...这是工作,如果我不包括'json'$ .get()函数...但是,如果我包括'JSON',没有任何事情发生 – CuriousCoder 2011-01-31 01:58:36

1

肯定。如果将它放入<p></p>对中,会更容易,但是您对数据所做的操作是将其放入DOM节点中。 jQuery非常乐意让您再次获得这些DOM节点的结果out

但是你可以让生活对自己更容易,如果你有PHP回报JSON,像

[ question, ans1, ans2, ans3, ans4] 

,甚至更好,因为

{ "question" : "my question text", 
    "answers" : [a1,a2,a3,a4] 
} 
0

在PHP中可以存储在一个阵列响应,并使用json_encode函数转换它。在jQuery之前,您可以使用$ .parseJSON检索json(数据)

0

您必须使用jQuery.parseJSON这个..

例如:

"var obj = jQuery.parseJSON('{"name":"John"}'); 
alert(obj.name === "John");" 

click me to know briefly