問題描述
我是 JavaScript 編程新手.我現(xiàn)在正在開發(fā)我的 Google Chrome 擴(kuò)展程序.這是不起作用的代碼...:P
I'm new to JavaScript programming. I'm now working on my Google Chrome Extension. This is the code that doesn't work... :P
我想讓 getURLInfo
函數(shù)返回它的 JSON 對(duì)象,并且想把它放到 resp
中.有人可以修復(fù)我的代碼以使其正常工作嗎?
I want getURLInfo
function to return its JSON object, and want to put it into resp
. Could someone please fix my code to get it work?
function getURLInfo(url)
{
var xhr = new XMLHttpRequest();
xhr.open
(
"GET",
"http://RESTfulAPI/info.json?url="
+ escape(url),
true
);
xhr.send();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
return JSON.parse(xhr.responseText);
}
}
}
var resp = getURLInfo("http://example.com/") // resp always returns undefined...
提前致謝.
推薦答案
你在這里處理一個(gè)異步函數(shù)調(diào)用.結(jié)果在到達(dá)時(shí)處理,而不是在函數(shù)完成運(yùn)行時(shí)處理.
You are dealing with an asynchronous function call here. Results are handled when they arrive, not when the function finishes running.
這就是回調(diào)函數(shù)的用途.當(dāng)結(jié)果可用時(shí)調(diào)用它們.
That's what callback functions are for. They are invoked when a result is available.
function get(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
// defensive check
if (typeof callback === "function") {
// apply() sets the meaning of "this" in the callback
callback.apply(xhr);
}
}
};
xhr.send();
}
// ----------------------------------------------------------------------------
var param = "http://example.com/"; /* do NOT use escape() */
var finalUrl = "http://RESTfulAPI/info.json?url=" + encodeURIComponent(param);
// get() completes immediately...
get(finalUrl,
// ...however, this callback is invoked AFTER the response arrives
function () {
// "this" is the XHR object here!
var resp = JSON.parse(this.responseText);
// now do something with resp
alert(resp);
}
);
注意事項(xiàng):
escape()
已被永遠(yuǎn)棄用.不要使用它,它不能正常工作.使用encodeURIComponent()
.- 您可以通過設(shè)置
open()
的async
參數(shù)使send()
調(diào)用同步為false
.這會(huì)導(dǎo)致您的 UI 在請(qǐng)求運(yùn)行時(shí)凍結(jié),而您不希望這樣. - 有許多庫(kù)旨在使 Ajax 請(qǐng)求變得簡(jiǎn)單而通用.我建議使用其中之一.
escape()
has been deprecated since forever. Don not use it, it does not work correctly. UseencodeURIComponent()
.- You could make the
send()
call synchronous, by setting theasync
parameter ofopen()
tofalse
. This would result in your UI freezing while the request runs, and you don't want that. - There are many libraries that have been designed to make Ajax requests easy and versatile. I suggest using one of them.
這篇關(guān)于我怎樣才能讓 XHR.onreadystatechange 返回它的結(jié)果?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!