【发布时间】:2011-07-24 13:48:00
【问题描述】:
我在互联网上找到了这段代码,它似乎可以工作,但无论我将加载到 DIV 中的文件命名为什么,总是得到相同的消息“找不到对象”我到底要做什么文件被加载?
这是 HTML 代码...
<a href="javascript:void()" onclick="javascript:sendRequest('sourcepage?id=34', 'targetdiv')">Link Text</a>
<div id="targetdiv">This is the target</div>
那么...我必须为“sourcepage?id=34”命名文件以使其正确?到目前为止,我已经尝试过“id34.html”“sourcepage-34.html”和类似的东西,但似乎都没有。
脚本:
function createRequestObject()
{
var returnObj = false;
if(window.XMLHttpRequest) {
returnObj = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
returnObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
returnObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return returnObj;
}
var http = createRequestObject();
var target;
// This is the function to call, give it the script file you want to run and
// the div you want it to output to.
function sendRequest(scriptFile, targetElement)
{
target = targetElement;
try{
http.open('get', scriptFile, true);
}
catch (e){
document.getElementById(target).innerHTML = e;
return;
}
http.onreadystatechange = handleResponse;
http.send();
}
function handleResponse()
{
if(http.readyState == 4) {
try{
var strResponse = http.responseText;
document.getElementById(target).innerHTML = strResponse;
} catch (e){
document.getElementById(target).innerHTML = e;
}
}
}
我认为这是我这辈子做过的最愚蠢的问题...抱歉,提前感谢:D
【问题讨论】:
-
你想在 div 中加载什么?
-
很难分辨是哪一个,但您的代码中的一些
Object是undefined。你需要找出它是哪一个。为此,您必须在代码中添加一些行,告诉您在哪里引发了Error,或者只需使用安装了 Firebug 的 Firefox。 -
我想加载一个外部 HTML,然后将它加载到一个带有链接的 DIV 中……而 Firebug 没有给我任何错误。
-
在
readyState后面加一行console.log("(!) response >> " + http.responseText)检查请求是否成功。
标签: javascript ajax html filenames getelementbyid