如何使用jquery ajax调用web方法

时间:2014-08-27 10:36:00

标签: javascript jquery asp.net ajax web-services

如何在jquery ajax中调用webservice,

client.aspx代码:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
     <html xmlns="http://www.w3.org/1999/xhtml">
      <head id="head1" runat="server">
      <title></title>
   <script type="text/javascript">
    $(document).ready(function () {
      $("#Hello").click(function(e)
      {
           alert("hello");
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Name.asmx/GetUserDetails",
                data: "{'name':'" + $("#txtename").val() + "'}",
                dataType: "json",
                async: false,
                success: function (data) {
                alert("success");
               $("#lbl").html(data);   

                }
            });
        }
        });
         </script>
     </head>
    <body>
<form id="form1" runat="server">
<div>
    <%--<asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/Name.asmx" />
        </Services>
    </asp:ScriptManager>--%>
    <input id="txtename" type="text" />
    <input id="Hello" type="button" value="Welcome" class="style2" onclick="javascript:return validate();" />
    <label id="lbl" />
</div>
 </form>
  </body>
     </html>

name.asmx代码:

           [System.Web.Script.Services.ScriptService]
        public class Name : System.Web.Services.WebService {
        public XmlElement GetUserDetails(string name)
      {
    con.Open();
    SqlCommand cmd = new SqlCommand("exec sp_n @name='" + name + "'", con);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.CommandText = "sp_n";
    cmd.Parameters.AddWithValue("@name", name);
    cmd.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();
    XmlDataDocument xmldata = new XmlDataDocument(ds);
    XmlElement xxx = xmldata.DocumentElement;
    return xxx;

   }   

如果我点击按钮只是显示警告框,但它没有输入ajax代码,我该怎么办, 我知道是否正在做crt请帮助我

0 个答案:

没有答案