JSON.parse:意外的角色

时间:2012-11-05 11:50:32

标签: php jquery json

我有一个json数组,我想在java脚本中解析它但我的jquery给了我以下错误:

JSON.parse: unexpected character 

jquery中的代码,错误来自:

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {//error comes on this line.
return window.JSON.parse( data );
} 

我的代码是:

success: function(msg){
                var test= JSON.parse(msg);
                var question=test.question;
        document.getElementById('question').value=question;

我使用的是最新版本的jquery

 <script src="http://code.jquery.com/jquery-latest.js"></script>

我在功能(msg)中得到了这个:

[Object { question=

"What is your religious affiliation?"

,  userQuestionCategoryId=

"1"

}]

这是我的Php代码:

function getquest()
        {
             $id=$this->input->post('qid');
             $data=$this->adminsetting->getquestion($id);
             if(count($data)>0)
             //echo $data[0]->question; 
             echo json_encode($data);
             else
             echo "No Question In database";
        }

提前致谢。

2 个答案:

答案 0 :(得分:1)

此:

{ question=

"What is your religious affiliation?"

,  userQuestionCategoryId=

"1"

}

必须是这样的:

{"question":"What is your religious affiliation?",  "userQuestionCategoryId":"1"}

答案 1 :(得分:1)

实际上json我已经解析了所以我必须使用索引,我缺少使用索引msg [0]。这就是我遇到问题的原因。

success: function(msg){



        document.getElementById('question').value=msg[0].question;

        document.getElementById('id').value=msg[0].userQuestionCategoryId;
        //alert(msg);
        } });