【问题标题】:How to call JS function through ajax call如何通过ajax调用调用JS函数
【发布时间】:2013-10-11 23:50:02
【问题描述】:

我想通过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 页面时没有收到警报消息。这里出了什么问题,需要做什么?

【问题讨论】:

标签: javascript jquery ajax jsp


【解决方案1】:

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

一旦 ajax 调用被调用,你应该在主页而不是 ajax 页面上触发一个函数

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

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

【讨论】:

  • 能否请您告诉我如何从 test.jsp 页面调用 hello() 函数。你的意思是我需要创建一些短链接或按钮来触发 hello() 函数吗?我想在加载 test.jsp 后调用此函数,而无需任何用户点击。感谢您的帮助!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-17
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    相关资源
    最近更新 更多