[英]How to get the response of XMLHttpRequest in javascript client?
我需要从Java脚本调用OpenMRS REST API来从OpenMRS获取数据。 以下是我的Java脚本代码:
function myfunction(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John Smith", true);
xhr.setRequestHeader("Authorization", "Basic YWRtaW46QWRtaW4xMjM");
xhr.send(null);
alert(xhr.responseXml);
}
当我使用凭据从浏览器调用给定的url时,我得到的XML响应如下所示:
<object>
<results>
<person>
<uuid>007037a0-0500-11e3-8ffd-0800200c9a66</uuid>
<display>John Smith</display>
<links>
<link>
<rel>self</rel>
<uri>
NEED-TO-CONFIGURE/ws/rest/v1/person/007037a0-0500-11e3-8ffd-0800200c9a66
</uri>
</link>
</links>
</person>
</results>
</object>
但是问题是,javascript警报消息带有值“ undefined”。 如果我通过Firebug分析网络流量,则HTML选项卡将显示200 OK成功消息,而XHR选项卡将显示“ URL:0请求,大小:0B”消息。 可以在Firefox Web控制台中检查同一件事,也就是没有响应。 我在这里找到了类似的讨论,但没有解决方案。 当直接从浏览器调用URL时,如何获取服务器发回的XML响应?
更新的代码:
function myfunction(){
function reqListener () {
console.log(this.responseXml);
}
var xhr = new XMLHttpRequest();
xhr.onload = reqListener;
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
xhr.open("GET", "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John Smith", true);
xhr.setRequestHeader("Authorization", "Basic YWRtaW46QWRtaW4xMjM");
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
// ...
} else {
// Unable to compute progress information since the total size is unknown
}
}
function transferComplete(evt) {
alert("The transfer is complete.");
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
xhr.send(null);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
alert("State: "+xhr.readyState+" and Status: "+xhr.status+" and Response: "+xhr.responseXml);
}
}
}
onreadystatechange
函数发出的警报显示State: 4 and Status: 0 and Response:Undefined
。 因此,“ Status
不为200,“ Response
为未定义。
您需要将函数(侦听器)分配给属性xhr.onload您可以在本文Mozilla开发人员网络中阅读有关使用XHR的更多信息。
在您的代码中进行以下更改,看看是否可以解决未定义的问题:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
alert("State: " + xhr.readyState + " and Status: " + xhr.status
+ " and Response: " + xhr.responseXML);
}
}
}
请注意xhr.responseXML
相比xhr.responseXml
在你的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.