2010-07-14 95 views

回答

2

为此,您可能需要添加JSON lib中旧版本的浏览器:

var json = JSON.parse('{"baseUrl":"\/","success":true}'); 
// or 
json = {"baseUrl":"\/","success":true}; 

alert(json.success) 
//or 
alert (json['success']) 

在jQuery的AJAX可以使用的dataType json。 这将直接解析代码,这样你会

/* Ajax Get-Request */ 
$.ajax({ 
    type  : 'get', 

    url  : "myurl.html", 

    dataType : 'json', 

    success : function (response) 
    { 
    alert (response.success) 
    alert (response['success']) 
    }, 

    // Internal Server Error/Timeout 
    error : function (XMLHttpRequest, textStatus, errorThrown) 
    { 
    alert ("Error \n" + textStatus); 
    } 

}); 

http://www.json.org/js.html

0

这里亚去。

var getJsonProperty = (function(){ 
    var hasJson = (window.JSON && JSON.parse && JSON.parse.call); 
    return hasJson ? function (jsonString, property) { 
    return JSON.parse(jsonString)[property]; 
    } : function (jsonString, property) { 
    return new Function("return ("+jsonString+")['"+property+"'];")(); 
    } 
})(); 


alert (getJsonProperty('{"baseUrl":"\/","success":true}', 'success')); 
// shows `true` 
+0

只有当您从可信来源获取JSON时才能执行此操作。 – 2010-07-14 06:45:24

+0

有没有人真的从他们认为可能对脚本进行脚本注入攻击的源中获取JSON?无论如何,这是与'JSON.parse'预兼容的,这很重要。它比替代方法'eval'更安全,因为它不在本地函数范围内执行。如果您愿意,您总是可以解析恶意内容的字符串,但在许多(大多数?)实际案例中,您将从可信来源获取内容。 – 2010-07-14 07:08:10