2013-10-02 28 views
0

我开始了与JS。 我想从XML服务器获取数据。我不知道如何发送请求,并通过JavaScript函数获取xml中的anser。 它说我需要一个POST请求,并在形式发送XML:的JavaScript:XMLHttpRequest的请求和服务器的答案

<?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?是请求建立以符合上述风格(或者我需要换行或转换为XML DOM的东西)?接收物如何工作。我做对了吗?那么变量答案是否包含带有答案的xml?

此代码是有点不工作。我将xml-string打印到控制台,它看起来就像上面一样(没有换行符)。但是handleRequest函数不会打印任何东西(它根本不会被调用)。

在此先感谢!

+0

1)如果它说你应该使用POST,然后使用POST。 2)是的。请求之前无法获得响应。 3)通过连接字符串来构建XML。 4)然后在该'postData'变量中发送XML字符串。 – Bergi

+0

<<< _2)是的。您在申请之前无法获得答复._ ** ** 1 ** – Lapsio

回答

0

看起来这是很好的媒体链接。 我得到了错误的clientID。基本上就是这样。再就是只是一个小的修改,以使:

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

..to送过来了XMLHttpRequest的功能。这对我有效。