douni9620
douni9620
2012-07-03 12:29

如何在没有onclick / onkeyup / onchange等的情况下调用Ajax函数

I am trying to include a .php file that will generate a form for me by picking out questions from a MySQL database. I've found numerous ways to call this function that I have called getQuestions() with 1 parameter (page number). I've seen drop down menus that will execute my php file using onchange, or buttons (onclick) etc. But is there a way to use my function without these? I just want it to automatically load with the rest of the page without any unnecessary interactions.

Don't know if this matters but my page is made in jQuery Mobile so it should only be visible when the correct page/div-id is active.

function getQuestions(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("page_1").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","generate_questions.php?p="+str,true);
    xmlhttp.send();
    }

These are the functions I have tried to use to view the .php within the rest of the HTML (without success)

<script type="text/javascript">
                    $(document).ready(function() {
                    getQuestions(1);
                    });
                    </script>


window.onload = function() {
                    $("#page_1").load(getQuestions(1));
                    }

window.onload = function() {
                    getQuestions(1);
                    }
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • duanrong6802 duanrong6802 9年前

    Seems I solved my problem by assigning the php code to a smaller div than originally planned. I can't assign it to the page id, but to a smaller div within the page. The odd thing is it seems I can't really generate new div's within the php code either, so that sort of limits it's usage.

    点赞 评论 复制链接分享
  • dongwei4096 dongwei4096 9年前

    Hello following way you can call the code without click or change

    just write down the function name between script tag and create that function after call the function.

    点赞 评论 复制链接分享
  • duancong2965 duancong2965 9年前

    you can do that on Window.onload or document.ready event.

    点赞 评论 复制链接分享
  • dongzi3805 dongzi3805 9年前

    You can use document ready event to load rest of the content:

    $(document).ready(function() {
       // your code
     });
    
    点赞 评论 复制链接分享

相关推荐