我正在尝试获取rest API的响应,但它返回null。 这是我的JS代码:
function submitApproval()
{
//alert('Approval Start');
var invocation = new XMLHttpRequest();
//alert('Get Url');
var url ='http://localhost:port/rest/bpm/wle/v1/task/303?parts=all';
send_with_ajax(url);
}
function send_with_ajax(url){
// alert('Send Start'+url);
var httpRequest = new XMLHttpRequest();
//alert("Start");
httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("Content-type", "application/xml");
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
httpRequest.setRequestHeader("X-Alt-Referer", "http://www.google.com");
alert("Send");
httpRequest.send();
alert('Send Request');
var _tempRecommendations = httpRequest.responseXML;
// window.alert(httpRequest.response)
//window.alert(httpRequest.responseText)
window.alert(_tempRecommendations);
/*
httpRequest.onreadystatechange = function() {
alert('onLoad call');
if (httpRequest.readyState == 4)
{
var _tempRecommendations = httpRequest.responseXML;
window.alert(httpRequest.response)
window.alert(httpRequest.responseText)
window.alert(_tempRecommendations)
}
};*/
}
我该怎么做?我尝试过onload和onreadystatechange但结果相同。
答案 0 :(得分:1)
您应该在设置onreadystate处理程序之后发送请求,以确保在收到响应之前设置处理程序。
// set this first
httpRequest.onreadystatechange = function() {
window.alert(httpRequest.responseText);
};
// and then
httpRequest.send();
答案 1 :(得分:1)
Here is working Demo。检查readystate
事件
onreadstatechange
function test(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
}
test();