有四个问题,我在这里看到:你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