【问题标题】:Document.ready() functionDocument.ready() 函数
【发布时间】:2011-12-15 09:38:32
【问题描述】:

这是我的ajax函数

<script language="JavaScript" type="text/javascript">
 var num = 1;
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";



hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {

        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (++num)); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";

}

现在我也找到了正确的 div/class 来运行 ajax 函数:

 $('.eventcontainer.button').click(function() { 
    $.post('javas.php', function(data) {
       $(this).parent('div').find('.status').html(data);
    })
    });

但是我不确定在我的代码中的哪里实现这个

【问题讨论】:

  • 把它放在 $(document).ready(function () {} 中就可以了
  • document.ready函数从哪里来的?
  • 如果您将点击处理程序附在准备好的文档中,它将正常工作。你可以把整个代码放在那里,它就可以工作了。
  • 这只是确保 DOM 已加载,您已经将处理程序附加到按钮。
  • 如果有jquery,为什么还要使用自己的ajax方法?

标签: php javascript jquery css ajax


【解决方案1】:

如果您想在多个浏览器上运行您的代码,那么编写自己的 ajax 请求并不是一个好主意。如果您手头有 jQuery,并且想要一个后 ajax 请求,请使用 jQuery 函数:

$.post('ajax/test.html', function(data) {
    $('.result').html(data);
});

【讨论】:

    【解决方案2】:

    准备使用的文档示例:

    function fooBar() {
    //some code
    }
    
    $(document).ready(function(){
    // all your jquery in here
    $('body').hide().fadeIn(2000);
    // or call your own functions
    fooBar();
    });
    

    【讨论】:

      【解决方案3】:

      你可以用这个:

      $(function(){
          $('.eventcontainer.button').click(function() { 
              $.post('javas.php', function(data) {
                  $(this).parent('div').find('.status').html(data);
              })
          });
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 2011-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多