繁体   English   中英

使用AJAX加载时,jQuery插件无法正常工作吗?

[英]Jquery plugin doesn't work when loading with AJAX?

我使用jquery自动滚动博客文章。它们通常可以正常工作,但是当我通过AJAX加载该页面时它不能滚动或完全不起作用。问题可能是我如何调用ajax来加载页面。是我不正确的回调函数问题? 这是我正在使用的ajax代码:

  function loadme() {
   var xhttp;
   if (window.XMLHttpRequest) {
   xhttp = new XMLHttpRequest();
   } else {
   xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {

  document.getElementById("loadcontent").innerHTML = this.responseText;
  }
 };
  xhttp.open("GET", "http://xxxyyy.com/blogs/", true);
  xhttp.send();
 }

它们都可以工作,但是jquery post自动滚动将不起作用。这是由于回调函数引起的吗? 我不确定。有人建议或更正代码。

另外我做了替代的回调函数,但是那也不起作用。

 <div id="loadcontent"> Content to load/replace</div>

 <button onclick="loadDoc('http://xxxyyy.com/blogs', myFunction)">Browse 
 Blogs</button>

 //ajax with callback function

 function loadDoc(url, cFunction) {
 var xhttp;
 xhttp=new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
 if (this.readyState == 4 && this.status == 200) {
  cFunction(this);
  }
 };
 xhttp.open("GET", url, true);
 xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("loadcontent").innerHTML =
xhttp.responseText;
}

由于您已经标记了jquery并且在anwser中还提到了jquery,因此我提供了一个jquery解决方案。

//bind click event to the button, set an id for the button to make it just for that particular button
$(button).click(function() {
    ajaxRequest("url", loadcontent);
});


// this will be the function for ajax, with the callback as parameter
function ajaxRequest(url, callback) {
    $.ajax({
        url: url,
        method: "get",

        success: function (response) {
            callback(response);
        },

        error: function (jqXHR, exception) {
             // handle errors
        }
    });
}

// this will be passed as callback to the ajaxRequest function
//you just need to set the innerHTML and the use animate to scroll to the bottom or to whatever height you would like
function loadcontent(message) {
    $("#loadcontent").html(message);
    $("#loadcontent").animate ({ scrollTop: $("#container").prop("scrollHeight") }, 10);
}

暂无
暂无

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

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