2012-07-24 67 views
0

我試圖將其通過javascript來編輯使用PHP數據查詢,編輯JSON字符串在PHP

我的Ajax請求的樣子

var totalSearchResult=10; 
$.ajax({ 
    url:"php/queryManipulation.php", 
    type: 'POST', 
    data: { totalQuery : totalSearchResult, query : '{"data":{"match_all":{}}}'}, 

    success: function(finalList) 
    { 
     alert(finalList); 
    } 
}); 

我的PHP代碼看起來像

<?php 
$from=$_POST["totalQuery"]; 
$qry=json_decode($_POST["query"]); 
$qry->from=$from; }?> 

我試圖讓它在表格中,

{"data": {"match_all": {}} , "from": 10} 

我得到錯誤Object of class stdClass could not be converted to string

+0

...問題是? – deceze 2012-07-24 08:33:04

+1

你忘了'json_encode'它回來了嗎? – 2012-07-24 08:34:01

+0

爲什麼我會在PHP腳本的末尾看到額外的'}'? – 2012-07-24 08:36:58

回答

3

編輯:改變json_decode返回從數組值對象

你需要在完成編輯後再次對json進行編碼。 所以你可以做的是這樣的:

<?php 
    $from   = $_POST["totalQuery"]; 
    $qry    = json_decode($_POST["query"]); 
    $qry->data->from = $from; 
    //you will get the new json string 
    //as the finalList variable in your post callback 
    echo json_encode($qry); 
?> 
+0

我以{「data」:{「match_all」:[]},「from」:「10」}的形式得到它......它應該像{「data」:{「match_all」:{}}, 「from」:「10」} – user1371896 2012-07-24 08:42:14

+0

我改變了答案。現在試試。 – Ignas 2012-07-24 08:44:20

0

可以解碼到一個數組(不知道對象)和重新編碼:

$qry = json_decode($_POST['query'], TRUE); 
$qry['from'] = 10; 
$new_qry = json_encode($qry);