js转为json的方法
在字符串两端再加上括号然后eval就ok了。测试代码如下:
在jQuery中JSON最基本的格式:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
异步获取数据:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
<script type="text/javascript">
<script type="text/javascript">
<!--
var a=50,b="xxx";
var arr="{id:"+a+",name:'"+b+"'}";
arr=eval('('+arr+')')
alert(arr.name);
//-->
</script>
<!--
var a=50,b="xxx";
var arr="{id:"+a+",name:'"+b+"'}";
//-->
</script>
var a=50,b="xxx";
var arr="{id:"+a+",name:'"+b+"'}";
//-->
</script>
<script type="text/javascript">
<!--
var a=50,b="xxx";
var arr="{id:"+a+",name:'"+b+"'}";
arr=eval('('+arr+')')
alert(arr.name);
//-->
</script>
在jQuery中JSON最基本的格式:
$.getJSON('ajax/test.json', function(data) {
$('.result').html('<p>' + data.foo + '</p>'
+ '<p>' + data.baz[1] + '</p>');
});
将一字符串解析成JSON对象(比eval好多了):var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
异步获取数据:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});