Sau*_*rma 434 javascript json
我在解析简单的JSON字符串时遇到问题.我在JSONLint上检查了它们,它表明它们是有效的.但是当我尝试使用其中任何一个JSON.parse或jQuery替代解析它时,它会给我错误unexpected token o:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用json_encode()PHP编写我的字符串.
Dar*_*con 777
您的数据已经是一个对象.无需解析它.javascript解释器已经为您解析了它.
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);
Run Code Online (Sandbox Code Playgroud)
小智 70
尝试解析所以:
var yourval = jQuery.parseJSON(JSON.stringify(data));
Run Code Online (Sandbox Code Playgroud)
小智 14
使用JSON.stringify(data);:
$.ajax({
url: ...
success:function(data){
JSON.stringify(data); //to string
alert(data.you_value); //to view you pop up
}
});
Run Code Online (Sandbox Code Playgroud)
Pla*_*tor 11
但是,错误的来源是您需要将完整的JSON字符串放在引号中.以下将修复您的样本:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
正如其他受访者所提到的,该对象已经被解析为JS对象,因此您无需解析它.要演示如何在不解析的情况下完成相同的操作,您可以执行以下操作:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details.ques_title);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Shu*_*ing 10
cur_ques_details 已经是一个JS对象,你不需要解析它
小智 5
当我使用jQuery AJAX提交数据时遇到了同样的问题:
$.ajax({
url:...
success:function(data){
//server response's data is JSON
//I use jQuery's parseJSON method
$.parseJSON(data);//it's ERROR
}
});
Run Code Online (Sandbox Code Playgroud)
如果响应是JSON,并且您使用此方法,则获得的数据是JavaScript对象,但如果使用dataType:"text",则数据是JSON字符串.然后使用$.parseJSON是好的.
| 归档时间: |
|
| 查看次数: |
647037 次 |
| 最近记录: |