4

我想通过ajax post call来调用jsp文件。所以我完成了下面的代码 -

  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>

现在 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>

问题是,打开我的第一个 html 页面时,我没有收到警报消息。这里有什么问题,需要做什么?

4

2 回答 2

2

不要尝试使用 onload 函数,而是使用 ready 函数作为

    $( document ).ready(function() 
    {
        //here you can call hello function
    })
于 2014-05-29T11:37:17.303 回答
0

当您像这样进行 ajax 调用时,您不会执行 javascript。

一旦进行了ajax调用,您应该在主页上而不是在ajax页面上触发一个函数

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

    success: function(){
        hello();
    },
    error: function(){
        alert("error");
    }
});
function hello()
{
}
于 2013-10-04T20:44:48.170 回答