将javascript get函数添加到href

时间:2012-04-22 05:41:17

标签: javascript ajax

我对此非常陌生

我有这个链接:

<a onclick = sendRequest('GET','room_chart.jsp') href=#>Show Chart</a>

但我需要在该链接中生成动态地址。

我创建了javascript:

    <script language="javascript">
        var selectedOption;
        var ROOM;
        var BUILDING;

        function GetLink(){
            selectedOption = document.getElementById("roomandbuildingid").options[e.selectedIndex].text;  //getting selected option
            ROOM = selectedOption.split("|")[0].trim().split(":")[1].trim(); //parsing text
            BUILDING = selectedOption.split("|")[1].trim().split(":")[1].trim(); //parsing text
            return "'room_chart.jsp?room="+ROOM+"&building="+ BUILDING+"'"; //returning url
        }
    </script>

但是当我将功能粘贴到它中时 - 它不起作用!

<a onclick = sendRequest('GET',GetLink()) href=#>Show Chart</a>

现在,在调试之后,我发现实际上它创建了正确的srting,但不知怎的,我的函数不愿意接受它作为URL!这是一个相当矛盾 - 它创建了正确的字符串 - 如果我将其硬编码到代码中 - 它的工作原理!但是来自变量的动态链接 - 不起作用!

请帮忙!

见下文: 我的js文件:

function createRequestObject(){
    var req;
    if(window.XMLHttpRequest){
        //For Firefox, Safari, Opera
        req = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        //For IE 5+
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        //Error for an old browser
        alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
    }
    return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequest(method, url){
    if(method == "get" || method == "GET"){
        http.open(method,url);
        http.onreadystatechange = handleResponse;
        http.send(null);
       // alert( document.URL );
       // document.write (GetLink());
    }
}
function handleResponse(){
    if(http.readyState == 4 && http.status == 200){
        var response = http.responseText;
        if(response){  
            document.getElementById("ajax_res").innerHTML = response;
        }
    }      
}

1 个答案:

答案 0 :(得分:0)

好的,该函数正确地返回所有内容,解析没有正确完成。我修好了它。我很难调试JavaScript。