jquery asp.net, stopping postback

喜你入骨 提交于 2019-12-13 04:32:14

问题


I have a text box and I want the user to be able to type in the TextBox and when they hit enter, I want jQuery to make a ajax call to a web method.
The problem is, when user hits the enter, the method is called but then the page refreshes due to the return. I've tried using return false but with no results.

Here is the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=7" />  
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script language="javascript">
   function serviceCall(getText) {          
      $.ajax({
       type: "POST",
       url: 'ActiveDirectoryAutoFillWebService.asmx/TestMethod',
       data: "{'getId':'+ getText +'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
       $("#divResult").html(msg.d);
       },
       error: function (e) {
       $("#divResult").html("WebSerivce unreachable " + e.name + " " + e.message);
     }
   });  
  //  return false;       This does not work      
}
function searchKeyPress(e) {
   if (typeof e == 'undefined' && window.event) { e = window.event; }
       if (e.keyCode == 13) {              
           serviceCall(e)   
           //  return false;       This does not work         
       }          
 }
 </script>
</head>
<body>

<form id="form1" runat="server">      
    <div id="divResult" style="margin-top: 20px;"></div>
    <asp:TextBox ID="tbSearchName" runat="server" onKeyPress="searchKeyPress(event); "></asp:TextBox>      

</form>
</body>
</html>

If anyone knows how I can accomplish this, please let me know.


回答1:


Have a look at the following functions on the event object:

  • stopImmediatePropagation
  • stopPropagation
  • preventDefault

In your case, you can use

e.preventDefault()

This will stop the default action from happening.



来源:https://stackoverflow.com/questions/16145989/jquery-asp-net-stopping-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!