2013-02-17 99 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