2012-04-03 80 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