我有一个[可能很愚蠢]的问题,但我搜索了又搜索,但仍然没有找到答案。
我创建了一个函数,用于容纳对服务器的 httprequest 调用,并将 POST 方法的 Web 服务 URL 和参数传递到该函数中。我调用该网络球的事件处理函数必须对响应执行某些操作。
不幸的是,调用网络调用函数后的代码在我获得所需的值之前就执行了,这会导致巨大的错误。我的代码如下所示:
function process_stuff() {
do_stuff;
var d = webcall(link, params);
if (d == "OK") {
do_stuff2;
}
}
function webcall(link, params) {
//httprequest...;
return responseText;
}
对 d 的检查失败,因为它在填充 d 之前执行 if 语句,因此 d 保持未定义或为 null。请帮忙。如何让代码等待 d 填充来自网络调用的值?
编辑:
这是根据您的评论编写的代码:
function checker () {
var d; // declare d here so it is global among process_logic() and give_alert()
function process_logic(callback) {
var params = "func=" + encodeURIComponent("webcalls");
params += "&text=" + encodeURIComponent("yadda");
var linker = "http://www.wigital.co.za/test/test.php";
d = webcall(params, linker, callback);
alert(d + ' on line 63');
}
function give_alert(d) {
if (d == "OK") {
alert("Success");
} else {
alert("not so sure... " + d);
}
}
//process_logic(give_alert(d));
process_logic(give_alert());
}
function webcall(a, link) {
// a = paramaters string, link is the URL of the web service
//alert(callback);
var d;
var x = new XMLHttpRequest();
/* What to do when server responds - define this before sending to server */
x.onreadystatechange = function () {
/* Error check */
if (x.readyState === 4 && x.status !== 200) {
return("PROBLEM: " + x.response);
}
/* Process response */
if (x.readyState === 4 && x.status === 200) {
//alert("I have a return value");
return x.responseText;
//alert(x.responseText);
//d = x.responseText;
}
};
/* send to server */
x.open("POST", link, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.send(a);
/*
if (typeof callback === 'function') {
callback(d);
}*/
}
我希望填充函数 Give_alert() 中的变量 d。它目前未定义,因为在 webcall() 完成并返回值之前,give_alert() 正在执行...
最佳答案
我强烈建议将回调函数传递到网络请求中。
function process_stuff() {
do_stuff;
webcall(link, params, callback);
}
function callback(data){
do_stuff2;
}
function webcall(link, params, callback) {
//httprequest...;
//on success
callback(response)
}
关于javascript - 如何与httprequest同步执行Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251648/