2012-04-03 160 views
0

使用該無法解析JSON

var res = eval('(' + response + ')'); 

response包含[{"total_sections":"3"}]此值不能解析JSON。但我不能採取值total_sections

function changeSection() { 
    id = document.getElementById('layoutDropdown').value; 
    $.ajax({ type: "POST", 
      url:'/manage', 
      data: {id : id }, 
      success: function(response){ 
        alert(response); 
        var res = eval(response); 
        alert(res[0].total_sections);      
      } 
    }); 
} 

管理佈局:

public function manageLayouts() { 
     $id = $_POST['id']; 
     $data = $this->managelayoutmodel->getSections($id); 
     echo json_encode($data); 
} 
+0

你應該避免使用函數eval(),在這裏閱讀原因:http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea和這裏http ://javascript.crockford.com/code.html – 2012-04-03 05:56:27

+0

'alert(typeof response)'的結果是什麼?'在調用eval之前? – scessor 2012-04-03 06:05:37

+0

猜測,你剛剛在通話中錯過了[[0]]?它應該可以通過'res [0] .total_sections' – Christoph 2012-04-03 06:09:54

回答

0

如果responsestring可以解析與var res = eval(response);的JSON(但它是不是很好),var res = JSON.parse(response);或者如果你使用jQuery var res = $.parseJSON(response)。否則,如果它已經是object,則不需要解析它,只設置var res = response;
現在您可以通過致電res[0].total_sections,例如,你可以用alert(res[0].total_sections);進行測試。

+0

雅了明白了.....謝謝uuuuu :) – keerthi 2012-04-03 06:06:33

+0

@Anupama:不客氣。如果你能[接受答案](http:// meta。stackexchange.com/questions/5234/how-does-accepting-an-answer-work)的所有問題。 – scessor 2012-04-03 06:16:46

+0

@scessor停止推動用戶接受答案時,甚至沒有解決問題... – Christoph 2012-04-03 06:25:55

0

嘗試在新的瀏覽器使用JSON.parse(response)。對於較舊的瀏覽器使用json2.jsJSON.parse(response)

+0

在新瀏覽器中嘗試。它仍然undefined – keerthi 2012-04-03 06:03:20

1

你應該總是儘量避免使用eval,它是邪惡的!

你有2種選擇:

如果響應是一個字符串:

var res = JSON.parse(response); 

,或者如果它已經是一個JSON-對象(例如通過設置您的返回類型AJAX調用JSON)

var res = response; 

然後你可以通過res[0].total_sections訪問總節。

編輯:您的代碼中有幾個問題:

id = document.getElementById('layoutDropdown').value;前加var。旁註:您正在使用jQuery,因此訪問會更容易:$("#layoutDropdown").val();

您是否碰到過alert(response)?如果沒有,你的阿賈克斯呼叫是不成功的。您應該添加一個error塊來捕獲錯誤:http://api.jquery.com/jQuery.ajax/

執行console.log(響應)並檢查結果。它是否具有您想要的正確值? (你也可以檢查一下ajax-call的主體)。

很可能,eval(response)和訪問res[0].total_sections都不是您麻煩來自的部分。

+0

我剛剛嘗試使用var res = JSON.parse(response);這..但沒有得到 – keerthi 2012-04-03 06:11:14

+0

張貼您的整個代碼,所以我們可以看到,你正在嘗試做什麼。 – Christoph 2012-04-03 06:16:08

+0

keerthi 2012-04-03 06:18:02