先不管跨域问题
+-------------------------------------
test.php
echo '{"name":"tom","tel":"123456"}';这个就输出一个json的字符串,
+-------------------------------------
然而jquery的
   $.getJSON('test.php',function(d){
        alert(d.name)//输出tom
             })
是如何把这个json字符串变成了json对象了??jquery里边根本没有json_decode之类的函数,可是却把一个json字符串转换为json对象了

解决方案 »

  1.   

    jquery源代码里用eval()将字符串转成对象了if ( type == "json" )
    data = eval("(" + data + ")");
      

  2.   

    因为json本身就是js对象的一个子集。
      

  3.   

    就是类似于这样的:<script type="text/javascript">var $ = {}$.getJson = function(s, callback) {
      if(typeof s != 'string') {
        return;
      }
      var json = {};
      try {
        json = eval('(' + s + ')');
      } catch (e) {
        alert('[ERROR]\n' + e.message);
      }  
      callback.call(this, json);
    }window.onload = function() {
      var s = '{"name":"tom","tel":"123456"}';
      $.getJson(s, function(d) {
          alert(d.name);
        });
    }
    </script>
      

  4.   

    看一下源码吧: getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
    },
    get: function( url, data, callback, type ) {
    // shift arguments if data argument was ommited
    if ( jQuery.isFunction( data ) ) {
    callback = data;
    data = null;
    } return jQuery.ajax({
    type: "GET",
    url: url,
    data: data,
    success: callback,
    dataType: type
    });
    }, // Build temporary JSONP function
    if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
    jsonp = "jsonp" + jsc++; // Replace the =? sequence both in the query string and the data
    if ( s.data )
    s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
    s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure
    // that a JSONP style response is executed properly
    s.dataType = "script"; // Handle JSONP-style loading
    window[ jsonp ] = function(tmp){
    data = tmp;
    success();
    complete();
    // Garbage collect
    window[ jsonp ] = undefined;
    try{ delete window[ jsonp ]; } catch(e){}
    if ( head )
    head.removeChild( script );
    };
    }