使用AJAX加载Jquery插件时不起作用?

时间:2017-04-28 18:36:20

标签: javascript php jquery html 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发布自动滚动将无法正常工作..这是由于回调功能?我不确定..有人建议或更正代码......会感谢志愿者的帮助

加成 我做了替代回调功能,但这也不起作用..

 <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;
}

1 个答案:

答案 0 :(得分:0)

既然你已经标记了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);
}