JavaScript:xmlhttprequest请求和服务器答案

时间:2013-10-02 16:05:11

标签: javascript xml xmlhttprequest

我开始使用js。 我想用xml从服务器获取数据。我想知道如何发送请求,并通过JavaScript函数获取xml中的anser。 它说我需要一个POST-Request并以下面的形式发送一个xml:

 <?xml version="1.0" encoding="UTF-8"?> 
<ft> 
    <request clientId="123" apiName="api_search_location_stops_nearby" apiVersion="2.0"> 
        <client clientId="123"/> 
        <requestType>api_search_location_stops_nearby</requestType> 
        <outputCoords>WGS84</outputCoords> 
        <fromCoordName>WGS84</fromCoordName> 
        <fromType>coords</fromType> 
        <fromWgs84Lat>48.22</fromWgs84Lat> 
        <fromWgs84Lon>16.39</fromWgs84Lon> 
    </request> 
</ft> 

然后获得xml答案。它有2个或3个节点,我很感兴趣。从那以后,它就没什么大不了的了。

这是维也纳公共交通公司的一个奇怪的API: http://akirk.github.io/Wiener-Linien-API/ 我基本上想从他们那里得到(打开)数据。

下面: https://techscreen.tuwien.ac.at/node/794 我找到了php的解决方案..

我的尝试:

 // Bare bones XML writer - no attributes
function xmlElement(name,content){
    var xml
    if (!content){
        xml = '<' + name + '>' + '</' + name + '>'
    }
    else {
        xml = '<'+ name + '>' + content + '</' + name + '>'
    }
    return xml
}



function sendRequest()
{
    var xmlReq
    xmlReq = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    xmlReq = xmlReq + "<ft>";
    xmlReq = xmlReq + "<request clientId=\"123\" apiName=\"api_get_monitor\" apiVersion=\"2.0\">";
    xmlReq = xmlReq +      "<client clientId=\"123\"/>";
    xmlReq = xmlReq + xmlElement("requestType", "api_get_monitor");
    xmlReq = xmlReq + xmlElement("monitor",
                                 xmlElement("outputCoords", "WGS84") +
                                 xmlElement("type","stop") +
                                 xmlElement("name","60201040") +
                                 xmlElement("year","2013") +
                                 xmlElement("month","10") +
                                 xmlElement("day","3") +
                                 xmlElement("hour","8") +
                                 xmlElement("minute","0") +
                                 xmlElement("line") +
                                 xmlElement("sourceFrom","stoplist") );
    xmlReq = xmlReq + "</request>" + "</ft>";

    text1.text = xmlReq;


    var xhr = new XMLHttpRequest();
    xhr.onload = handleRequest;
    xhr.open("POST", "http://webservice.qando.at/2.0/webservice.ft"); // POST or GET
    xhr.send(xmlReq);
    // xhr.responseXML // this is allways null

}


function handleRequest(answer)
{
    console.log(answer.responseType);
    console.log(answer.responseXML);
}

我的问题的核心要点:在我的代码中,是否应该有GET或POST?请求是否符合上述风格(或者我是否需要换行或转换为DOM xml)?接收的东西是如何工作的。我这样做了吗?那么变量应答是否包含带有答案的xml?

这段代码不知何故不起作用。我将xml-string打印到控制台,它看起来就像上面一样(没有换行符)。但handleRequest函数不会打印任何内容(根本不会调用它)。

提前致谢!

1 个答案:

答案 0 :(得分:0)

看起来它已经很好了。 我得到了错误的clientID。基本上就是这样。然后只做了一个小修改:

xhr.onreadystatechange = function(){ page.handleRequest(xhr); }

..将xmlHttpRequest发送到函数。这对我有用。

相关问题