2014-03-04 76 views
1

我想在while或for循环中调用jsonpcallback函数。但我得到异步结果。如何在jsonpcallback中实现这一点。请帮助我解决这个问题或提供任何其他解决方案。如何获得jsonpCallback的同步结果?

window.onPublitoryOebPart = function(json) { 
    window.publitoryOebPartJson = json; 
    content = patchEditedContent(json); 
    saveOebPartToc(content); 
} 
i = 0; 
while(i < $("#oeb_parts_count").val()) { 
    return unless $("#oeb-part-file-url-"+i).length > 0 
    fileUrl = $("#oeb-part-file-url-"+i).html(); 
    $.ajax({ 
     url: fileUrl, 
     crossDomain: true, 
     dataType: "script", 
     jsonpCallback: "onPublitoryOebPart" 
    }) 
    i++; 
} 

回答

0

的JavaScript 不能得到一个 “同步” JSONP结果。这是因为JSONP涉及创建一个新的脚本元素;这种动态创建的脚本元素只能异步加载资源。

的JSONP请求刚刚use the success callback和处理响应异步。如果服务不允许指定动态函数,手动指定jsonpCallback仅为必需/有用。

如果在循环中使用success回调,则对read up on closures(然后read more)也很重要。

例如:

var i = 0; // Don't forget the "var" 
while(i < $("#oeb_parts_count").val()) { 
    var elm = $("#oeb-part-file-url-"+i); 
    if (!elm.length) { return; } // Make sure to use valid syntax 
    var fileUrl = elm.html(); 
    $.ajax({ 
     url: fileUrl, 
     crossDomain: true, 
     dataType: "script", 
     success: function (i, fileUrl) { 
      // Return a closure, the i and fileUrl parameters above 
      // are different variables than the i in the loop outside. 
      return function (data) { 
       // Do callback stuff in here, you can use i, fileUrl, and data 
       // (See the links for why this works) 
       alert("i: " + i + " data: " + data); 
      }; 
     })(i, fileUrl) // invocation "binds" the closure 
    }); 
    i++; 
} 

这可能是更清洁简单地通过创建一个名为功能的关闭,但是这一切都同一个概念。


同步XHR请求也非常不鼓励; XHR是而不是 JSONP,即使这些请求也是使用jQuery.ajax函数创建的。

+0

那么如何做到这一点?有可能在jsonpcallback函数中传递i值吗? – user2138489

+0

@ user2138489只需使用'success'回调(jQuery将合成代理函数)并异步处理结果*。您可能还需要阅读关闭,但最终结果是相同的 - JSONP *必须*异步使用。 – user2864740

+0

是的,我尝试了成功,但它没有锻炼。但我不确定我的尝试是否正确。我只是在成功函数中给出了alert json,但却没有定义 – user2138489