我的代碼:爲什麼不用XMLHttpRequest和document.write這個代碼工作?
var req = new XMLHttpRequest();
req.open("GET","http://http://surfkid.redio.de/link.php");
req.send(null);
var textout = var.responseText;
document.write(textout);
在文件中,沒有文字。
我做錯了什麼?
我的代碼:爲什麼不用XMLHttpRequest和document.write這個代碼工作?
var req = new XMLHttpRequest();
req.open("GET","http://http://surfkid.redio.de/link.php");
req.send(null);
var textout = var.responseText;
document.write(textout);
在文件中,沒有文字。
我做錯了什麼?
req.open("GET","http://http://surfkid.redio.de/link.php");
有虛假額外http://
。在任何情況下,除非當前網頁本身由surfkid.redio.de提供,由於同源策略,否則這將不起作用,所以假設情況是這樣,您不需要指定服務器名稱在所有。 (如果不是這種情況下,你將不得不對JSONP讀了。)
是一個異步的XMLHttpRequest。對此請求的迴應將不會馬上提供;你必須添加一個事件監聽器到req.onreadystatechange
。
另一種方法是一個額外的, false
參數傳遞給open()
,以獲得一個同步請求。但是同步的XMLHttpRequest通常被認爲是一件壞事,因爲它會鎖定瀏覽器UI直到獲取響應。
var textout = var.responseText;
你的意思是req
。
document.write(textout);
document.write
一般最好避免。例如,如果在內容完全加載後調用當前文檔,則會刪除當前文檔,如果您在異步XMLHttpRequest上使用回調,則會出現這種情況。
更容易將responseText
寫入元素的innerHTML
(假設響應應該是標記;如果不是創建具有給定文本值的文本節點)。
<div id="redio-link"></div>
<script type="text/javascript">
// Fix up missing XMLHttpRequest in IE6. You only need to do this once.
//
if (!window.XMLHttpRequest && 'ActiveXObject' in window) window.XMLHttpRequest= function() {
return new ActiveXObject('MSXML2.XMLHttp');
};
// Fetch link
//
var req= new XMLHttpRequest();
req.onreadystatechange= function() {
if (this.readyState===4)
document.getElementById('redio-link').innerHTML= this.responseText;
};
req.open('GET', '/link.php');
req.send();
</script>
你不能得到var.responseText
,你必須從請求得到它。
另外document.write
是一個函數,所以通過它從請求對象的字符串。
document.write(req.responseText)
但說實話,看使用像jquery一個框架,將時間節省你從長遠來看。
$.ajax({ url: "http://http://surfkid.redio.de/link.php", context: document.body, success: function(data){
document.write(data);
}});
:固定代碼..你不處理唉...回報也,當我試圖讓你的腳本,我得到一個錯誤,所以我取代自己的網頁。
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
document.write(this.responseText);
}
req.open("GET","http://api.fatherstorm.com/test/redio_result.php");
req.send();
sorrry,但這並沒有在我的鉻擴展 – user422039 2010-11-10 20:56:15
這就是爲什麼你需要使用像jQuery的框架。否則,你必須處理一百萬個瀏覽器不兼容問題。 – 2010-11-10 20:58:45
不工作....... – user422039 2010-11-10 21:07:25