2016-02-19 64 views
1

我目前正试图实现以下操作,并按顺序执行工作流程: 1.检索包含重定向URI/URL(如果成功)的URL。 2.使用检索到的URL打开新窗口,该窗口基本上重定向回到同一页面,但现在URL的后面附加了'code = randomCode'。 3.解析出randomCode作为别的东西的输入。jQuery推迟的承诺似乎不适用于打开新窗口

问题: 在这一刻,我使用jQuery承诺首先$ .get(number 1),.then(do number 2),.then(do number 3)。

问题是,这整个功能只能在一次失败后出现。即每次刷新时,第一次打开新窗口,但其他部分不会成功,即randomCode不会被成功解析出来,因为在那个阶段,jQuery无法检测到打开的窗口,即使它应该因为它正在使用。

但是,第一次失败后,一旦打开窗口,每次后续尝试都能成功地检索到所有内容。

这是怎么回事?有人可以帮忙吗?我的代码示例如下:

var retrievedURL; 
var desiredString; 
function getURL() { 

    $(document).ready(function() { 
     $.get(firstURL) // assume valid URL 
       .then(function(response) { 
        $('#url').html('Click this'); 
        $('#url-link').attr("href",response.url); 
        retrievedURL = response.url; 
       }) 
       .then(function() { 
        newWindow = window.open(retrievedURL ,'test'); 
       }) 
       .then(function() { 
        desiredString = newWindow.location.search.substr(6); 
       }) 


    }) 
} 

所以这就是函数的要点。我当然会继续用desiredString做一些事情,但不知何故,每一次,第一次运行,desiredString都是null。

+1

删除的getURL功能。这是防止你的代码被绑定到document.ready – Oisin

+0

试了一下,然后它运行在一个无限循环... –

回答

0

如果新窗口确实重定向那么你是不是占的时间为它做这样的。您需要在新窗口中加载事件侦听器,然后获取URL

最后的then()不会等待新窗口加载它将几乎立即被调用。您将需要从第二then()返回一个承诺,有最后的then()火这一承诺得到解决

后尝试

$.get(firstURL) // assume valid URL 
      .then(function(response) { 
       $('#url').html('Click this'); 
       $('#url-link').attr("href",response.url); 
       retrievedURL = response.url; 
      }) 
      .then(function() { 
       newWindow = window.open(retrievedURL ,'test'); 
       // listen for window to load 
       newWindow.onload = function(){ 
        desiredString = newWindow.location.search.substr(6); 
        // do something with desiredString 
       } 
      }) 
+0

YESSSSS它工作我爱你。老兄,我认真地花了几天时间,你就解决了它! –

0

删除getURL函数。这是防止你的代码从被绑定到的document.ready 试试这个:

var retrievedURL; 
var desiredString; 
$(document).ready(function() { 
    $.get(firstURL) // assume valid URL 
    .then(function(response) { 
     $('#url').html('Click this'); 
     $('#url-link').attr("href",response.url); 
     retrievedURL = response.url; }) 
    .then(function() { 
     newWindow = window.open(retrievedURL ,'test'); 
    }) 
    .then(function() { 
     desiredString = newWindow.location.search.substr(6); 
    }) 
}); 
+0

,导致无限循环... –

+0

以什么方式?什么部分在呼唤自己? – Oisin

+0

erm,打开的新窗口只是在原始窗口保持新的检索代码的情况下刷新...以及在那里没有任何反应。我不确定发生了什么,但新打开的窗口不断刷新并检索新代码。 –