【问题标题】:Replace DIV content Javascript, can't get the external filename right替换 DIV 内容 Javascript,无法正确获取外部文件名
【发布时间】: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 &gt;&gt; " + http.responseText)检查请求是否成功。

标签: javascript ajax html filenames getelementbyid


【解决方案1】:

您尝试使用的文件名没有扩展名。根据其他服务器的配置,可以将其重新路由到许多不同的文件类型。 “?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
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多