Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
显示Javascript Ajax Web服务请求_Javascript_Ajax - Fatal编程技术网

显示Javascript Ajax Web服务请求

显示Javascript Ajax Web服务请求,javascript,ajax,Javascript,Ajax,我试图在HTML中显示来自web服务的ajax请求。 我可以在控制台中显示结果,但无法检索结果,然后在HTML中显示它。 我想通过单击“询问天气”按钮,在“天气结果”div中显示请求的结果。 她是我的密码。 谢谢大家 const askWeather=函数(结果){ var request=new XMLHttpRequest(); request.onreadystatechange=函数子函数(){ if(this.readyState==XMLHttpRequest.DONE&&this

我试图在HTML中显示来自web服务的ajax请求。 我可以在控制台中显示结果,但无法检索结果,然后在HTML中显示它。 我想通过单击“询问天气”按钮,在“天气结果”div中显示请求的结果。 她是我的密码。 谢谢大家

const askWeather=函数(结果){
var request=new XMLHttpRequest();
request.onreadystatechange=函数子函数(){
if(this.readyState==XMLHttpRequest.DONE&&this.status==200){
result=JSON.parse(this.responseText);
返回result.current_condition.condition;
}
};
请求。打开(“获取”https://www.prevision-meteo.ch/services/json/paris");
request.send();
}
const ask=document.getElementById('ask-weather');
ask.addEventListener('click',function()){
const weatherResult=document.getElementById('weather-result');
weatherResult.innerHTML=askWeather();
});

这是巴黎南部吗?
函数getJSON(路径){
返回新承诺(功能(解决、拒绝){
var xhttp=newXMLHttpRequest();
xhttp.open('GET',path,true);
xhttp.onreadystatechange=函数(){
if(this.readyState==4){
if((this.status>=200&&this.status<300)| | this.status==304){
var response=JSON.parse(this.responseText);
决心(回应);
}否则{
var error=this.statusText;
拒绝(“Http/App错误:”+错误);
}
}
}
xhttp.onerror=进程错误;
xhttp.onabort=进程错误;
xhttp.send();
xhttp=null;
函数processError(err){
拒绝(“网络错误:”+错误目标状态);
}
});
}
const ask=document.getElementById('ask-weather')
const weather=document.getElementById('weather-result')
常数端点https://www.prevision-meteo.ch/services/json/paris'
ask.addEventListener('click',function()){
getJSON(端点)。然后((成功)=>{
const response=success.current_condition.condition
weather.innerHTML=响应
},(错误)=>{
console.log(错误)
})
})

这是一个使用Promise的简单示例。请参阅工作说明。

这似乎是一个异步/回调问题。单击按钮时,它会在某处发送请求并立即返回(如果出现上述代码,则返回
未定义的
——可通过将其保存在变量和
控制台.log
中进行检查)

调用
askWeather()
时,它本身可能返回一些内容。
请求中的
返回
。onreadystatechange
无法为
askWeather
返回,因为它发生了多次或更晚-在
askWeather
完成并发送请求之后

如果向函数传递一个变量并将其设置为函数体中的新值,则不会为调用方更改该变量。这意味着如果您想传递一个变量并通过内部函数设置它,那么执行
result=…
并没有真正的帮助

有必要采用不同的方法来处理这一问题。以下是一些备选方案:

  • 要使其与您的代码最为相似,您可以在
    onreadystatechange
    函数中设置
    innerHTML
  • 让它更通用,让askWeather使用回调(在“完成”时调用函数):
  • (a) 让askWeather返回一个承诺,并在调用者中使用它
  • (b) 除了Promise解决方案之外,在较新的浏览器中已经有了
    async
    await
    语法:
  • 不要使用
    XMLHttpRequest
    ,而是使用
    fetch
    API,如果您支持的浏览器中有承诺,则通常应该可以使用该API。解决办法在原问题的评论中。对于大多数现代浏览器,这应该可以工作:
  • 如果您不必支持IE,我将使用fetch替代方案


    我希望其他替代方案能够清楚地说明,异步模式可以用JavaScript解决。

    欢迎使用堆栈溢出!是否有理由这样做
    weatherResult.innerHTML=askWeather()
    ?如果您不返回XMLHttpRequest的结果,而只是在处理程序中更改innerHTML(
    子函数
    ),事情可能会更好。您知道,异步而不是同步。它的API更干净,并且得到广泛支持
    fetch(“https://www.prevision-meteo.ch/services/json/paris)然后(res=>res.json())。然后(data=>document.getElementById('ask-weather')。innerHTML=data.current\u condition.condition)
    function getJSON(path) {
      return new Promise(function(resolve, reject) {
        var xhttp = new XMLHttpRequest();
    
        xhttp.open('GET', path, true);
        xhttp.onreadystatechange = function() {
          if (this.readyState === 4) {
            if ((this.status >= 200 && this.status < 300) || this.status === 304) {
              var response = JSON.parse(this.responseText);
    
              resolve(response);
            } else {
              var error = this.statusText;
    
              reject('Http/App Error: ' + error);
            }
          }
        }
        xhttp.onerror = processError;
        xhttp.onabort = processError;
        xhttp.send();
        xhttp = null;
    
        function processError(err) {
          reject('Network Error: ' + err.target.status);
        }
      });
    }
    
    const ask = document.getElementById('ask-weather')
    const weather = document.getElementById('weather-result')
    const endpoint = 'https://www.prevision-meteo.ch/services/json/paris'
    
    ask.addEventListener('click', function() {
      getJSON(endpoint).then((success) => {
        const response = success.current_condition.condition
    
        weather.innerHTML = response
      }, (error) => {
        console.log(error)
      })
    })
    
    const askWeather = function() {
      var request = new XMLHttpRequest();
      request.onreadystatechange = function subFunction() {
        if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
          const result = JSON.parse(this.responseText);
          // set it here directly
          const weatherResult = document.getElementById('weather-result');
          weatherResult.innerHTML = result.current_condition.condition;
        }
      };
      request.open("GET", "https://www.prevision-meteo.ch/services/json/paris");
      request.send();
    }
    
    const ask = document.getElementById('ask-weather');
    ask.addEventListener('click', function() {
      askWeather();
    });
    
    const askWeather = function(callback) {
      var request = new XMLHttpRequest();
      request.onreadystatechange = function subFunction() {
        if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
          const result = JSON.parse(this.responseText);
          // send the result to the passed "callback" function
          callback(result.current_condition.condition);
        }
      };
      request.open("GET", "https://www.prevision-meteo.ch/services/json/paris");
      request.send();
    }
    
    const ask = document.getElementById('ask-weather');
    ask.addEventListener('click', function() {
      askWeather(function (result) { // this whole function is the "callback" parameter
        const weatherResult = document.getElementById('weather-result');
        weatherResult.innerHTML = result;
      });
    });
    
    const askWeather = () => new Promise((resolve, reject) => {
      var request = new XMLHttpRequest();
      request.onreadystatechange = function subFunction() {
        if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
          const result = JSON.parse(this.responseText);
          // send the result to the passed "callback" function
          resolve(result.current_condition.condition);
        }
        // not sure about the error path here, but something like this:
        if (this.readyState == XMLHttpRequest.DONE && this.status != 200) {
          reject(new Error("There was an error with the XMLHttpRequest!"));
        }
      };
      request.open("GET", "https://www.prevision-meteo.ch/services/json/paris");
      request.send();
    });
    
    const ask = document.getElementById('ask-weather');
    ask.addEventListener('click', function() {
      askWeather()
        .catch((err) => weatherResult.innerHTML = err.message) // to handle possible errors, maybe?
        .then((result) => { // like the callback solution, but as promise!
          const weatherResult = document.getElementById('weather-result');
          weatherResult.innerHTML = result;
        });
      });
    });
    
    ask.addEventListener('click', async function() {
      try {
        const result = await askWeather(); // this "pauses" until the Promise return of `askWeather` resolves (or throws an error if it doesn't)
        const weatherResult = document.getElementById('weather-result');
        weatherResult.innerHTML = result;
      } catch (e) {
        // error could be handled here
      }
    });
    
    ask.addEventListener('click', async () => {
      const response = await fetch("https://www.prevision-meteo.ch/services/json/paris");
      const result = await response.json();
      const weatherResult = document.getElementById('ask-weather');
      weatherResult.innerHTML = result.current_condition.condition;
    });