简体   繁体   English

用javascript返回HTTP响应

[英]Returning the HTTP response in javascript

I am using XMLHttpRequest in javascript to make HTTP request to a local server. 我在javascript中使用XMLHttpRequest向本地服务器发出HTTP请求。 This is the code I am using. 这是我正在使用的代码。

var xhr = new XMLHttpRequest();
xhr.open("POST", "//localhost:5000/translate", true); 
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.send(JSON.stringify({"sentence":str}));


xhr.onreadystatechange = processRequest;

function processRequest(e)
{
  if (xhr.readyState == 4)
  {
    console.log('trans_res set');
    trans_res = xhr.responseText; // here trans_res is a global variable
    return String(xhr.responseText);
  }
}

I want this function to return the responseText so that I can use it some where else. 我希望此函数返回responseText,以便可以在其他地方使用它。

For that I tried two methods, 1) I tried returning the response and printing the response in console 为此,我尝试了两种方法:1)我尝试返回响应并在控制台中打印响应

var temp = function(string)
console.log(temp)

but the temp variable is coming as undefined in console, mostly I think it is because before it comes to console.log it is not yet set (response not returned) 但是temp变量在控制台中来时未定义,主要是我认为这是因为在进入console.log之前尚未设置(未返回响应)

2) I put a global variable (trans_res) and set it in the function and print it 2)我放入一个全局变量(trans_res)并将其设置在函数中并打印

var temp = function(string)
console.log(trans_res)

however it is also coming as undefined. 然而,它也即将变得不确定。

How can i ensure that I return the response, It's all right if i need to halt the execution somewhere in between, but I want a valid response. 我如何确保我返回响应,如果我需要在两者之间的某个地方暂停执行,那么可以,但是我想要一个有效的响应。

You need a new screwdriver. 您需要新的螺丝刀。 You send a request to amazon with your postbox (trans_res) where to send to. 您使用邮箱(trans_res)发送到的位置向亚马逊发送请求。 Amazon is working asynchron to you. 亚马逊正在与您异步。 If you look some minutes later in your postbox, you'll not find a screwdriver. 几分钟后,如果您在邮箱中查找,则找不到螺丝刀。 An hour later, too. 一个小时后,也是。 The problem with a "postbox" is, you don't know the time to look at. “邮箱”的问题是,您不知道要看的时间。

You have to to do the work (showing, changing, informing), when readyState gets 4. 当readyState变为4时,您必须进行工作(显示,更改,通知)。

I think the answer by @Holger is somewhat correct. 我认为@Holger的回答有些正确。 You are checking for a return value before its actually generated by function. 您正在检查返回值是否在函数实际生成之前。 Sometimes there are long processes which take time to generate the value. 有时要花很长时间才能产生价值。 Either you should focus on making the function faster or you should keep checking the returned value. 您应该专注于使函数更快,或者应该继续检查返回的值。

Use if-else statements to check the value. 使用if-else语句检查该值。 When its not undefined, log it. 如果未定义,请记录它。 You can use a loading wheel animation on users' side if it is related to UX. 如果与UX相关,则可以在用户端使用加载轮动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM