简体   繁体   English

如何通过Ajax调用来调用JS函数

[英]How to call JS function through ajax call

I want to call a jsp file through ajax post call. 我想通过ajax调用来调用jsp文件。 So I've done below code - 所以我完成了以下代码-

  xmlhttp=new XMLHttpRequest();

   xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {  
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
   }

   var params = "report_id=0&id=1234567890";
  xmlhttp.open("POST","/test/jsp/test.jsp",true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

      xmlhttp.setRequestHeader("Content-length", params.length);
      xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(params);
   }
   </script>
    </head>
<body onload="loadXMLDoc()">
 <div id="myDiv"></div>

Now test.jsp looks like below - 现在test.jsp如下所示-

  <html>  
  <head>
   <script language="JavaScript">
   function hello()
   {
   alert("Hello");
   //Do my stuff
    }
   </script>
     <title>test Page</title>

  </head>
    <body topmargin="0" leftmargin="0" onload="hello()">
  <form name="mainForm" >
  </form>
  </body>
  </html>

Issue is, I'm not getting alert message when opening my first html page. 问题是,打开我的第一个HTML页面时,我没有收到警告消息。 What is wrong here and what needs to be done? 这里有什么问题,需要做什么?

Instead of trying with onload function, use ready function as 与其尝试使用onload函数,不如使用ready函数作为

    $( document ).ready(function() 
    {
        //here you can call hello function
    })

you will not get javascript executed when you are making ajax call like this. 当您进行这样的ajax调用时,您将不会执行JavaScript。

Once ajax call is made you should trigger a function on main page not on ajax page 一旦进行了ajax调用,您应该在主页上而不是ajax页面上触发一个函数

 $.ajax({
    type: "POST",
    url: "test.jsp",

    success: function(){
        hello();
    },
    error: function(){
        alert("error");
    }
});
function hello()
{
}

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

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