2011-05-06 28 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); 
相關問題