有四個問題,我在這裏看到:你XMLHttpRequest
,你到一個<textarea>
書寫文字的方法,你得到一個<select>
當前所選值的方法,以及你的函數共享相同的名稱作爲一個ID(一個問題只在IE中)。
AJAX不像以前那樣工作,就像那樣不幸。相反,您必須跳過一些環節才能獲得請求運行並返回其responseText。以下是一些示例代碼:
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function() {
// When the server has returned a response, and it is good, we're ready
if (xhr.readyState === 4 && xhr.status === 200) {
// do something with xhr.responseText
}
};
// Three arguments: type of request, url, and should the request be async
xhr.open("GET", "url here", true);
xhr.send(null);
這是一個非常簡單的示例,但它的確展示了通用概念。有關AJAX的更多信息,請參閱開始AJAX時的MDC'S excellent tutorial。
接下來,在DOM中沒有write
函數用於<textarea>
。爲了改變什麼在textarea的,你需要使用它的value
屬性:
your_textarea.value = "something here";
或者,如果你要追加新的文本到文本區域:
your_textarea.value += "something here";
這將正確地插入文本。第三,確定當前所選<option>
在<select>
中的值的方法也行不通(不幸的是)。爲了抓住當前選擇的選項的值,你必須使用一個<select>
的selectedIndex
財產以及其options
屬性:
your_select.options[your_select.selectedIndex].value;
這將正常返回當前選定的選項的值。
最後,這只是IE中的一個問題,您的功能與ID共享同一個名稱。在IE中,任何ID都被全局定義爲DOM元素,所以這是一個問題。所以,簡單地將你的函數的名稱改爲別的東西應該可以緩解這個問題。
所有功能於一切,這是我認爲的代碼作品(雖然未經測試):
<script type='text/javascript'>
function select_change() {
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function() {
// When the server has returned a response, and it is good, we're ready
if (xhr.readyState === 4 && xhr.status === 200) {
var file = "includes/ads/" + xhr.responseText + ".txt.";
document.ads.descrip.value += file;
}
};
// Three arguments: type of request, url, and should the request be async
xhr.open("GET",
document.ads.subject.options[document.ads.subject.selectedIndex].value,
true);
xhr.send(null);
}
</script>
<form name="ads" method="post" action="scripts/del_advert_script.php">
<label>Advertisements by subject:</label><select name="subject" id="sub" onchange="select_change()">
//PHP Block that works
</select>
<textarea id="descrip" name="description" cols="100" rows="3" readonly="readonly">
</textarea>
<br />
<input type="submit" value="Submit" />
</form>
到底是什麼問題? – 2011-06-02 22:59:18
如果你在IE中這樣做,問題可能是你有一個id =「descrip」的textarea,請嘗試更改該id。 – david 2011-06-02 23:05:45
您的JavaScript函數中的代碼沒有任何意義 - 您正在創建一個XMLHttpRequest對象,將該對象放入一個字符串中,並嘗試「寫入」TEXTAREA。你想達到什麼目的? – duskwuff 2011-06-02 23:06:52