将PHP json_encode数组发送到jQuery

好吧,我想我需要帮助! 我搜索了我能想到的每一个关键词,但我仍然无法弄清楚,请帮忙。 我更像是一个php人,我刚开始使用jQuery。

基本上,我想要做的是从点击function发送一个jQuerypost。 并根据我的php函数返回的内容,显示/隐藏2个div。 我的php函数返回一个带有2个简单值的“json_encode”数组,如:

// ================== PHP代码============================ ======

$message_for_user = "blah blah"; $calculatedValue = 1230; $responseVar = array( 'message'=>$message_for_user, 'calculatedValue'=>$calculatedValue ); echo (json_encode($responseVar)); 

// ================== PHP代码结束=========================== =======

我的javascript代码应该接受php返回的值:

// ================== Javascript代码============================ ======

 $("div.calculator_result").click(function() { $.post('myCalculator.php' ,{qid:itemID},function(response) { $("div.calculation_value").show(500).html(response['calculatedValue']); $("div#message_for_user").show(500).html(response['message']); } } 

// ================== Javascript代码结束=========================== =======

不幸的是,在我的项目的javascript方面,div没有更新我的PHP函数返回的值….我在哪里错了? 我希望我的问题清楚,如果没有,请告诉我,我将提供所需的任何额外信息。

另一件事是,早些时候,我只回显一个值,即计算值(echo $ calculatedValue),一切正常,它只是在我转移到json编码数组中的echo之后,事情不起作用

 var json = $.parseJSON(response); alert(json.message); 

尝试设置dataType选项:

 $.post('myCalculator.php' ,{qid:itemID},function(response) { $("div.calculation_value").show(500).html(response['calculatedValue']); $("div#message_for_user").show(500).html(response['message']); }, 'json'); 

NB我还添加了右括号)你错过了它们。

您必须解析JSON响应。 jQuery具有这种内置function(幸运的是,因为IE6和7本身不支持JSON)。 设置一个等于这个的变量:

 $.parseJSON(response) 

然后,如果您不熟悉JSON格式,请检查响应标头(使用Firebug或类似方法),这将帮助您选择所需的键值。 如果你正在循环,我会在解析响应后调查in语句 。

编辑:使用$ .getJSON ,解析自动完成。 写得少,做得更多。 🙂

所有你必须做的,它告诉Ajax调用你正在接收数据类型“json”。 换一种说法…

 $.ajax({ url: "external_file", method:"post", dataType: "json", // **************** Note dataType**************** success:function(response){ console.log(response) // Response will be a javascript array, instead of a string. }, error: function(){ alert('something went wrong.') } })