2016-05-22 30 views
1

出於某種原因,「p」返回爲未定義。我將如何讓它返回數組?在函數中獲取請求和返回值

function doT() { 
    var pe; 
    $.get("https://www.google.com", function(data) { 
    pe = ["a", "b", "c"]; 
    }); 
    return pe; 
} 

var p = doT(); 
setTimeout(function() { console.log(p.length); }, 1200); 
+1

DoT不會返回任何內容 - 您爲什麼期望得到任何結果? –

+0

現在確實如此。我只是把setTimeout放在了請求尚未完成的情況下,並且它返回了空白pe。 –

+1

可能的重複[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

回答

2

的方式之一,使用起來會promise(讀到它):

現在它去,因爲CORS拒絕塊(讀到它):

var promise = new Promise(function(resolve, reject) { 
 
    var pe; 
 
    $.ajax("https://www.google.com") 
 
    .done(function() { 
 
     pe = ["a", "b", "c"]; 
 
     resolve(pe); 
 
    }) 
 
    .fail(function() { 
 
     reject("error"); 
 
    }); 
 
}); 
 
promise.then(function(result) { 
 
    $("#testing").text(result); 
 
}, function(err) { 
 
    $("#testing").text(err); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="testing"></div>

只是要一個有效的ajax調用,它會工作。評論是否需要進一步解釋。

0
function doT() { 

    var pe = $.get("https://www.google.com", function(data) { 
    pe = ["a", "b", "c"]; 
    }); 

return pe; 
} 

alert(doT()); 
+0

你測試過了嗎? – digglemister

+0

通常情況下,如果答案包含解釋代碼的意圖的解釋,以及爲什麼解決問題而不介紹其他問題 –