2010-11-21 96 views
3

好吧,我想我需要幫助!我搜索了每一個我能想到的關鍵字,但我仍然無法弄清楚,請幫助。更多的是一個PHP的傢伙,我剛剛開始使用jQuery。發送PHP json_encode數組到jQuery

基本上,我想要做的是從點擊功能發送一個jQuery發佈。並根據我的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 code ================ ==================

$("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 code End ====================== ============

不幸的是,在我的項目的JavaScript方面,div不更新我的php函數返回的值....我錯在哪裏?我希望我的問題清楚,如果沒有,請告訴我,我會提供任何額外的信息。

另一件事是,我只是echo'ing只有一個值,這是計算值(echo $ calculatedValue),並且一切工作正常,它只有在我轉移到echo'in json encode數組後事情不工作

回答

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

根據你的回答,這是我試過的:var resp_object = $ .parseJSON(response); $( 「div.calculation_value」)HTML(resp_object.calculatedValue);不幸的是,這對我有幫助,夥伴。我在php版本5.2.14上,如果這有助於 – SIndhu 2010-11-21 23:19:36

+0

alrite,那是有效的。由於某些扭曲的原因,我有一個jQuery的版本比1.4.1更早,看起來jQuery.parseJSON只是在1.4.1 – SIndhu 2010-11-22 05:37:22

2

嘗試設置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我也加入了,你已經錯過了他們的右括號)

1

您必須解析JSON響應。 jQuery具有這種內置功能(謝天謝地,因爲否則IE6和7本身不支持JSON)。設置等於這個變量:

$.parseJSON(response) 

然後,如果你不熟悉JSON格式,檢查響應頭(使用Firebug或類似),這將幫助你挑選你想要的鑰匙值。如果你正在循環,一旦響應被解析,我會查看for in statements

編輯:使用$.getJSON,解析是自動完成的。少寫,多做。 :)

+0

中添加的,他需要的是POST – Kemo 2010-11-22 14:15:24

0

所有你必須做的,它告訴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.') 
    } 
})