在javascript ajax调用之后调用了一个jquery

Called a jquery after javascript ajax call

本文关键字:调用 一个 jquery javascript ajax 之后      更新时间:2023-09-26

我有这个返回ajax请求的javascript代码

function showUser(str)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("lister").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","popup.php?qq="+str,true);
xmlhttp.send();
}

我试图执行一个无法完成的jquery,除非ajax请求返回,但它不起作用

$('#scrollbar2').tinyscrollbar();

那么在 ajax 加载后我应该如何执行最后一个 jquery?

设置listerinnerHTML后将其放入回调中:

document.getElementById("lister").innerHTML = xmlhttp.responseText;
$('#scrollbar2').tinyscrollbar();

但是既然你有jQuery,为什么不使用它的Ajax功能呢?

$.ajax({
    url: "popup.php",
    data: { qq: str },
    dataType: "text",
    success: function(response) {
        $('#lister').html(response);
        $('#scrollbar2').tinyscrollbar();
    }
});

onreadystatechange回调中添加 jQuery 调用。 这样做的原因是 ajax 异步完成(根据其名称)。 可以这样想:

onAjaxComplete = function () {
    // this will run second
}
// this will run first

依赖于 ajax 调用结果的所有工作都必须在回调中。

此外,由于您无论如何都在使用jQuery,因此您不妨使用他们的ajax API,这要简单得多。

function showUser(str) {
    $.get("popup.php", "qq=" + str).done(function (responseText) {
        $("#lister").html(responseText);
        $("#scrollbar2").tinyscrollbar();
    });
}