jQuery是否内置了JSON支持?

Jas*_*vis 9 jquery json

jQuery是否内置了JSON支持,还是我必须使用像jquery.json-1.3.min.js这样的插件?

Vot*_*ple 9

是的,绝对是的.你可以这样做:

$.getJSON('/foo/bar/json-returning-script.php', function(data) {
    // data is the JSON object returned from the script.
});
Run Code Online (Sandbox Code Playgroud)


kar*_*m79 9

您还可以使用$ .ajax并将dataType选项设置为"json":

 $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: ({id : this.getAttribute('id')}),
      dataType: "json",
      success: function(json){
         alert(json.foo);
      }
   }
);
Run Code Online (Sandbox Code Playgroud)

此外,$ .get$ .post有一个可选的第四个参数,允许您设置响应的数据类型,例如:

$.postJSON = function(url, data, callback) {
    $.post(url, data, callback, "json");
};

$.getJSON = function(url, data, callback) {
    $.get(url, data, callback, "json");
};
Run Code Online (Sandbox Code Playgroud)