Javascript xhr不会从js调用
我正在使用phonegap,并试图在点击按钮时调用xhr帖子 我的流程转到方法调用,但不调用xhr代码,我无法理解原因。 这个电话看起来像:Javascript xhr不会从js调用,javascript,cordova,Javascript,Cordova,我正在使用phonegap,并试图在点击按钮时调用xhr帖子 我的流程转到方法调用,但不调用xhr代码,我无法理解原因。 这个电话看起来像: function fetchTags(){ console.log("Fetched url is:" + IMAGE_URL); //var url = "http://localhost:8080/echo"; var url ="http://localhost:8080/
function fetchTags(){
console.log("Fetched url is:" + IMAGE_URL);
//var url = "http://localhost:8080/echo";
var url ="http://localhost:8080/echo";
console.log("#1");
var xhr = new XMLHttpRequest();
console.log("#2");
xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
console.log("#3");
xhr.setRequestHeader("Content-type", "application/json");
console.log("#4");
xhr.open('POST', url, true);
console.log("#5");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response);
}else{
window.alert(xhr.status);
}
};
console.log("#5");
//var msg = "{'message' : '" + IMAGE_URL + "'}";
console.log("sending request");
xhr.send(JSON.stringify({"message" : "my msg"}));
}
按钮代码:
<button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
为了澄清这一点,我可以看到正在打印第一个console.log。但就是这样。之后什么也没发生 为了每个人的利益,问题不是javascript,而是使用localhost从phonegap调用
我不理解phonegap能够在本地主机上访问我的api的假设(不确定为什么会有这个愚蠢的想法),但是是的,使用主机的实际ip使它立即工作。我觉得有点讽刺,你会调用你的函数
fetchTags
,然后不要使用fetch
API。愿意打赌您的按钮在被单击时正在发布表单。页面刷新了吗?取消按钮单击或添加
,但随后它将打印第一个console.log,我认为这意味着它将进入该方法,并应完成其余的添加按钮代码。如果请求失败,我建议添加事件处理程序。类似于xhr.addEventListener(“错误”,onError);函数onError(evt){console.log(“传输文件时出错”);}
,并告诉我们结果。
Fetched url is:undefined
#1
#2
#3