[英]Replace DIV content Javascript, can't get the external filename right
我在互聯網上找到了此代碼,它似乎可以正常工作,但是無論我用什么名字命名要加載到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
那么,您要使用的文件名沒有擴展名。 根據其他服務器的配置,可以將其重新路由到許多不同的文件類型。 “?id = 34”是url參數,與文件名無關。 只需替換文件名:
<a href="javascript:void()" onclick="javascript:sendRequest('myFile.html', 'targetdiv')">Link Text</a>
<div id="targetdiv">This is the target</div>
並將文件命名為myFile.html並將其放置在與上述HTML相同的文件夾中。 如果您選擇使用jQuery,我建議您這樣做,您可以使用以下方法進行操作:
$('#targetdiv').load('myFile.html', function(){
// code to execute once the HTML is loaded into your div
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.