2013-02-17 126 views
0
(function() { 

    function callbackF(data) { 
     eval(data.script); 
    } 

    window.onload = function() { 
     if (url.indexOf('.html') > 0) { 
      var gt_widget_id = document.createElement('div'); 
      gt_widget_id.setAttribute('id', 'gt_widget_0'); 
      var comments = document.getElementById('comments'); 
      comments.parentNode.insertBefore(gt_widget_id, comments); 
      var comments = document.getElementById('comments'); 
      var script = document.createElement('script'); 
      script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url); 
      script.setAttribute("type", "text/javascript"); 
      script.setAttribute("id", "grazit_script"); 
      document.getElementById("gt_widget_0").parentNode.appendChild(script); 
     } 
    } 
})(); 

html與問題無關,標記確實附加,json返回就在調用之後,控制檯告訴我callbackF是未定義的?這是爲什麼?jsonp函數未定義

回答

1

這是爲什麼?

因爲你需要定義封閉地區以外的callbackF功能:

function callbackF(data) { 
    eval(data.script); 
} 

(function() { 
    window.onload = function() { 
     if (url.indexOf('.html') > 0) { 
      var gt_widget_id = document.createElement('div'); 
      gt_widget_id.setAttribute('id', 'gt_widget_0'); 
      var comments = document.getElementById('comments'); 
      comments.parentNode.insertBefore(gt_widget_id, comments); 
      var comments = document.getElementById('comments'); 
      var script = document.createElement('script'); 
      script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url); 
      script.setAttribute("type", "text/javascript"); 
      script.setAttribute("id", "grazit_script"); 
      document.getElementById("gt_widget_0").parentNode.appendChild(script); 
     } 
    } 
})(); 

另外,您可以定義在window範圍的callbackF功能,使其從封閉的外部訪問:

(function() { 
    window.callbackF = function(data) { 
     eval(data.script); 
    }; 

    window.onload = function() { 
     if (url.indexOf('.html') > 0) { 
      var gt_widget_id = document.createElement('div'); 
      gt_widget_id.setAttribute('id', 'gt_widget_0'); 
      var comments = document.getElementById('comments'); 
      comments.parentNode.insertBefore(gt_widget_id, comments); 
      var comments = document.getElementById('comments'); 
      var script = document.createElement('script'); 
      script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url); 
      script.setAttribute("type", "text/javascript"); 
      script.setAttribute("id", "grazit_script"); 
      document.getElementById("gt_widget_0").parentNode.appendChild(script); 
     } 
    } 
})(); 
+0

嗯..感謝達林,我以爲你只回答asp.net mvc的問題..我會嘗試你的方法。是因爲我把所有東西都包裹在封口中了嗎? – BlackFire27 2013-02-17 15:24:21

+1

是的,這是因爲您將整個方法封裝在閉包中,這意味着此函數只能從閉包中調用。除了你永遠不會在閉包中調用這個函數。您正在調用服務器端端點,該端點返回本身正在調用該函數的JSONP。而且,不,我不僅僅回答ASP.NET MVC問題。 – 2013-02-17 15:25:39