我有一个简单的问题,以下仅适用于IE 7及更高版本,如何才能使它在Firefox和Opera上运行?
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.tdsoft.se/index.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
修改
感谢您的所有答案,现在我还有另外一个关于后续代码的问题
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
现在我想搜索xmlhttp.responseText(换句话说,调用函数 loadXMLDoc())来获取关键字,比如“testfile”,如果它存在多个例子“testfile_1”和“testfile_2”.....“testfile_n”然后“doSomething”
像这样function searchADocument(wordToSearchFor){
int numberOfTimesWordOccurs=0;
var thePageToSearchThrough [] = loadXMLDoc();
for (i=0; i<thePageToSearchThrough.length; i++){
if(thePageToSearchThrough[i]==wordToSearchFor)
numberOfTimesWordOccurs++;
}
If (wordToSearchFor > 1)
document.write("<a href="http://selnc05.go.se:8080/component_test/build/testfile_1"> testfile_1</a>"<a href="http://selnc05.go.se:8080/component_test/build/testfile_2"> testfile_2</a><a href="http://selnc05.go.se:8080/component_test/build/testfile_n"> testfile_n</a>
)
Else
window.location="http://selnc05.go.se:8080/component_test/build/testfile.html";
}
我不知道从哪里开始,因为我不知道xmlhttp.responseText是什么类型,我可以将它存储在一个数组中并使用for循环扫描等吗? 提前致谢。 =)
答案 0 :(得分:0)
尝试这样的事情:
ajax("http://www.tdsoft.se/index.html", function(data) {
document.getElementById("myDiv").innerHTML = data;
});
<强>代码强>
function getXmlHttpObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status != 200) {
if (typeof onError == 'function') {
onError(this.responseText);
}
}
else if (typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}