如果我添加“警报”,则会发生无法解释的变化

发布于 2024-10-20 21:16:25 字数 1061 浏览 1 评论 0原文

请帮助解决这个问题: 在循环中,我首先调用一个函数,该函数将更改 DIV 的内容,然后尝试显示新内容。代码是(简单来说):

while (...){
    fetch(website_url);
//  alert("useless");
    x=document.getElementById("prova").textContent;
    alert(x);
}

“Fetch”是一个使用 jQuery 打开指定 URL 并将内容粘贴到 DIV“prova”中的函数。看到评论的“警报”了吗?如果我保留它的注释,“获取”工作完美(我在浏览器窗口中看到获取的代码),但第二个警报却没有!它显示了 PREVIOUS DIV 内容(即,第一次是空白的,在第二次迭代时将显示第一次迭代的内容,等等...)。 但是,如果我取消第一个警报的注释,第二个警报就可以正常工作。 它显然看起来像一个同步问题,但我尝试了很多方法(即超时,ifs,..),但我一直无法解决它。有什么建议吗?

这是 fetch 函数(实际上它不是我的......我只是在学习如何使用它)

function fetch(url){
  container = $('#prova');
  doAjax(url);

  function doAjax(url){
    $.getJSON("http://query.yahooapis.com/v1/public /yql?"+"q=select%20*%20from%20html%20where%20url%3D%22"+encodeURIComponent(url)+"%22&format=xml'&callback=?",
function(data){
    if(data.results[0]){
      var data = filterData(data.results[0]);
      container.html(data);
    } else {
      var errormsg = '<p>Error: could not load the page.</p>';
      container.html(errormsg);
    }
  }
}

please help on this issue:
Within a loop, I first call a function, which will change the content of a DIV, and then try to display the new content. The code is (in brief):

while (...){
    fetch(website_url);
//  alert("useless");
    x=document.getElementById("prova").textContent;
    alert(x);
}

"Fetch" is a function that uses jQuery to open the specified URL and paste the content in the DIV "prova". See the commented "alert"? If I keep it commented, the "fetch" works perfectly (I see the fetched code in the browser window) but the second alert doesn't! It shows the PREVIOUS DIV content (i.e., the first time it is blank, on the second iteration will show the content of the first iteration, etc ...).
However, if I uncomment the first alert, the second alert works fine.
It clearly looks like a synchronization issue, but I've tried in a lot of ways (i.e. with timeouts, ifs, ..) and I haven't been able to solve it. Any suggestion?

Here is the fetch function (actually it is not mine ... I'm just learning how to use it)

function fetch(url){
  container = $('#prova');
  doAjax(url);

  function doAjax(url){
    $.getJSON("http://query.yahooapis.com/v1/public /yql?"+"q=select%20*%20from%20html%20where%20url%3D%22"+encodeURIComponent(url)+"%22&format=xml'&callback=?",
function(data){
    if(data.results[0]){
      var data = filterData(data.results[0]);
      container.html(data);
    } else {
      var errormsg = '<p>Error: could not load the page.</p>';
      container.html(errormsg);
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

记忆里有你的影子 2024-10-27 21:16:25

您似乎完全忽略了 AJAX 是什么:您正在向 Yahoo 发出异步页面请求,这意味着您设置发出请求的浏览器,然后在等待时继续处理脚本。这就是全部目的。

在您设置呼叫后,响应文本不会立即可用,但是当您添加警报时,您将添加一个与人相关的延迟,该延迟恰好足够长在您的情况下,异步请求返回。

您可以使 AJAX 请求同步(“AJAX”作为“异步 Javascript 和 XML”是用词不当,最好称为 XmlHttpRequest):

var url = "http://query.yahooapis.com/v1/public /yql?"+"q=select%20*%20from%20html%20where%20url%3D%22"+encodeURIComponent(url)+"%22&format=xml'&callback=?";

// Your asynchronous call:
$.getJSON(url, function(data) { ... });

// A synchronous alternative:
$.ajax({
    type: 'GET',
    url: url,
    dataType: 'json',
    data: {},
    async: false,
    success: function(data) { ... },
  });

现在请求将在 之前完成(或失败) /em> 你的代码继续。

或者,如果您想保留异步请求,您可以将您希望在完成后发生的代码移动到回调函数中:

while (...) {
    function myFunction() {
        var x = document.getElementById("prova").textContent;
        alert(x);
    }
    fetch_and_handle(website_url, myFunction);
}

function fetch_and_handle(url, handler) {
    var container = $('#prova');
    var url       = "http://query.yahooapis.com/v1/public /yql?"+"q=select%20*%20from%20html%20where%20url%3D%22"+encodeURIComponent(url)+"%22&format=xml'&callback=?";

    $.getJSON(url, function(data) {
       if (data.results[0]) {
          var data = filterData(data.results[0]);
          container.html(data);

          if (handler != undefined) {
              handler();
          }
       }
       else {
          var errormsg = '<p>Error: could not load the page.</p>';
          container.html(errormsg);
       }
   });
}

我还在几个地方添加了 var:当您'要创建局部变量,请使用 var。我修复了一些缩进。

You seem to be completely ignoring what AJAX is here: you're making an asynchronous page request to Yahoo, which means you set the browser making the request, then continue processing your script while you wait. That's the entire purpose.

The response text is not available immediately after you set the call, but when you add an alert you're adding a human-dependent delay that just happens to be long enough for the asynchronous request to come back, in your case.

You could make the AJAX request synchronous ("AJAX" as "Asynchronous Javascript And XML" is a misnomer, and is better called XmlHttpRequest):

var url = "http://query.yahooapis.com/v1/public /yql?"+"q=select%20*%20from%20html%20where%20url%3D%22"+encodeURIComponent(url)+"%22&format=xml'&callback=?";

// Your asynchronous call:
$.getJSON(url, function(data) { ... });

// A synchronous alternative:
$.ajax({
    type: 'GET',
    url: url,
    dataType: 'json',
    data: {},
    async: false,
    success: function(data) { ... },
  });

Now the request will complete (or fail) before your code continues.

Or, if you want to keep the asynchronous request, you can move the code that you want to happen after it completes into the callback function:

while (...) {
    function myFunction() {
        var x = document.getElementById("prova").textContent;
        alert(x);
    }
    fetch_and_handle(website_url, myFunction);
}

function fetch_and_handle(url, handler) {
    var container = $('#prova');
    var url       = "http://query.yahooapis.com/v1/public /yql?"+"q=select%20*%20from%20html%20where%20url%3D%22"+encodeURIComponent(url)+"%22&format=xml'&callback=?";

    $.getJSON(url, function(data) {
       if (data.results[0]) {
          var data = filterData(data.results[0]);
          container.html(data);

          if (handler != undefined) {
              handler();
          }
       }
       else {
          var errormsg = '<p>Error: could not load the page.</p>';
          container.html(errormsg);
       }
   });
}

I've also added var in a few places: when you're creating a local variable, use var. And I fixed some indentation.

情绪失控 2024-10-27 21:16:25

此代码取决于时间。第一个警报会在获取完成期间产生延迟。

你想要做的是将 jQuery ajax 与回调一起使用,例如

$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

参见 http://api.jquery.com /jQuery.get/

This code depends on timing. The first alert creates a delay during which the fetch completes.

What you want to do is use jQuery ajax with a callback, e.g.

$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

see http://api.jquery.com/jQuery.get/

无人接听 2024-10-27 21:16:25

听起来你还没有理解什么是异步通信或者它是如何工作的。在您的代码中,当执行此行时:

x=document.getElementById("prova").textContent;

ajax 调用 (fetch()) 仍在运行。通过放置“无用”警报,ajax 调用有时间完成,因为以下行将等待您在执行之前单击“确定”。

为了解决这个问题,你有两种可能性:

  1. 将你的请求更改为同步(但这几乎每次都是一个坏主意)
  2. 使用ajax请求的成功回调来执行应该等待请求完成的代码

编辑:您还没有发布 fetch() 的代码,因此推测您正在其中使用 jquerys 的一些 ajax 函数...发布完整的代码那就太好了。

sound like you havn't understood what asynchronous communication is or how it works. in your code, when this line gets executed:

x=document.getElementById("prova").textContent;

the ajax-call (fetch()) is still running. by putting the "useless" alert in place, the ajax-call has the time to get completed, as the following line will wait for you to click "ok" before it gets executed.

to solve this, you have two possibilitys:

  1. change your request to be synchronous (but thats a bad idea almost every time)
  2. use the success-callback of your ajax-request to execute code that should wait for the request to finish

EDIT: you havn't posted your code for fetch(), so it's a matter of conjecture that you're using some of jquerys's ajax-function in there... posting the complete code would have been nice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文