【发布时间】:2013-10-02 16:05:10
【问题描述】:
我从 js 开始。 我想用 xml 从服务器获取数据。我想知道如何发送请求,并通过 javascript 函数获取 xml 中的分析器。 它说我需要一个 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 事物)?接收的东西是如何工作的。我这样做对吗?那么变量 answer 是否应该包含带有答案的 xml?
这段代码不知何故不起作用。我将 xml 字符串打印到控制台,它看起来就像上面一样(没有换行符)。但是 handleRequest 函数不打印任何东西(它根本不被调用)。
提前致谢!
【问题讨论】:
-
1) 如果它说您应该使用 POST,则使用 POST。 2) 是的。在请求之前您无法得到响应。 3) 通过连接字符串来构建 XML。 4)然后在
postData变量中发送XML字符串。 -
2) 是的。在请求之前您无法得到响应。 +1
标签: javascript xml xmlhttprequest