开发者

JSON decoding without each function

开发者 https://www.devze.com 2023-01-07 06:24 出处:网络
Hi All i hav开发者_Go百科e a json formatted out put as {\"baseUrl\":\"\\/\",\"success\":true} how get the value of success ??For this you might have to add the JSON lib for old browser versions:

Hi All i hav开发者_Go百科e a json formatted out put as

{"baseUrl":"\/","success":true}

how get the value of success ??


For this you might have to add the JSON lib for old browser versions:

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

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

In jQuery ajax you can use the dataType json. This will parse the code directly so you would have

/* 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


Here ya go.

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

精彩评论

暂无评论...
验证码 换一张
取 消