简体   繁体   中英

Replace DIV content Javascript, can't get the external filename right

I found this code on the internet and it seems to be working, but no matter what I name the file that will load into the DIV always get the same message that the "Object was not found" What exactly I have to do for the file to get loaded?

This is the HTML Code...

<a href="javascript:void()" onclick="javascript:sendRequest('sourcepage?id=34', 'targetdiv')">Link Text</a>
<div id="targetdiv">This is the target</div>

So... what do I have to name the file for the "sourcepage?id=34" to get it right? So far I have tried "id34.html" "sourcepage-34.html" and similar stuff, but none seems to work.

The script:

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;
        }   
    }
}

I think this is the most stupid question I've done in my life... sorry for that and thanks in advance : D

Well the file name that you're trying to use doesn't have an extension. Depending on the other server's configuration, that can be rerouted to a number of different file types. The "?id=34" is the url parameter, nothing to do with the file name. Just replace the file name:

<a href="javascript:void()" onclick="javascript:sendRequest('myFile.html', 'targetdiv')">Link Text</a>
<div id="targetdiv">This is the target</div>

And name your file myFile.html and place it in the same folder as where the above HTML is. If using jQuery is an option for you, I'd recommend it, you could do what you want with this:

$('#targetdiv').load('myFile.html', function(){
    // code to execute once the HTML is loaded into your div
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM