2011-05-06 29 views
0

我有下面的JSON(被剪下的空间),你可以在“测试”和“工具提示”中看到我有一个属性需要包含一个函数“formatter”(注意这个JSON是从XML读入的文件,并在.NET转换成JSON)函数 - 可能吗?

{ 
    "test": { 
     "formatter": function(){return '<b>'+ this.point.name +'<\/b>: '+ this.y +' %';} 
    }, 
    "title": { 
     "align": "center", 
     "text": "Your chart title here" 
    }, 
    "tooltip": { 
     "formatter": function(){return '<b>'+ this.point.name +'<\/b>: '+ this.y +' %';} 
    } 
} 

不幸的是,我产生了JSON文件的ASPX页面上收到一条错误

There was an error parsing the JSON document. The document may not be well-formed. 

这个错误是由于该位之后“格式化程序”不在引号中,因为它认为它是一个字符串。但如果我在它周围放置一个字符串,那么使用JSON的前端HTML页面将不会看到该函数。

是否可以将此函数作为函数传递而不是字符串?

非常感谢。


编辑:

感谢您的快速回信。正如我所说,我知道上述不正确的JSON,因为“function(){...}”部分不在引号中。读取JSON文件的前端是第三方,所以我想知道如何通过该函数,我了解注入(从SQL的角度来看)的问题,并理解为什么它不可能在JSON中JSON之前)。

+1

对我来说看起来不像是有效的json。 Json只是javascript的一个子集,而函数定义不是该子集的一部分。详细信息请查看json规范。 – CodesInChaos 2011-05-06 11:36:37

+2

JSON的重点在于它是一种不能包含可执行代码的数据格式。这是为了防止脚本注入攻击。 – 2011-05-06 11:37:55

+0

如有疑问,请使用http://jsonlint.com进行验证。 – Xion 2011-05-06 11:38:08

回答

2

如果您将其作为字符串传递给您,您可以使用使用Javascript EVAL函数,但EVAL为EVIL。

如何满足它的一半,并使用对象符号格式?

这是我在工作中使用的模板jquery插件,$ .fn.extend显示了这种标记格式。

/*jslint browser: true */ 
/*global window: true, jQuery: true, $: true */ 

(function($) { 

    var MyPlugin = function(elem, options) { 

     // This lets us pass multiple optional parameters to your plugin 
     var defaults = { 
      'text' : '<b>Hello, World!</b>', 
      'anotherOption' : 'Test Plugin' 
     }; 

     // This merges the passed options with the defaults 
      // so we always have a value 
     this.options = $.extend(defaults, options); 
     this.element = elem; 
    }; 

    // Use function prototypes, it's a lot faster. 
    // Loads of sources as to why on the 'tinternet 
    MyPlugin.prototype.Setup = function() 
    { 
     // run Init code 
     $(this.element).html(this.options.text); 
    }; 

    // This actually registers a plugin into jQuery 
    $.fn.extend({ 

     // by adding a jquery.testPlugin function that takes a 
      // variable list of options 
     testPlugin: function(options) { 

      // and this handles that you may be running 
        // this over multiple elements 
      return this.each(function() { 
       var o = options; 

       // You can use element.Data to cache 
          // your plugin activation stopping 
          // running it again; 
       // this is probably the easiest way to 
          // check that your calls won't walk all 
          // over the dom. 
       var element = $(this); 
       if (element.data('someIdentifier')) 
       { 
        return; 
       } 

       // Initialise our plugin 
       var obj = new MyPlugin(element, o); 

       // Cache it to the DOM object 
       element.data('someIdentifier', obj); 

       // Call our Setup function as mentioned above. 
       obj.Setup(); 
      }); 
     } 
    }); 
})(jQuery); 
相关问题