javascript 如何通过ajax调用调用JS函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19190391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:42:57  来源:igfitidea点击:

How to call JS function through ajax call

javascriptjqueryajaxjsp

提问by Pakira

I want to call a jsp file through ajax post call. So I've done below code -

我想通过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>

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. What is wrong here and what needs to be done?

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

回答by balaji

Instead of trying with onload function, use ready function as

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

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

回答by Bala

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()
{
}