0

在下面提到的代码中,只有当我使用 HTML 控件(按钮和文本)时,我才能设置从 ajax 调用获得的值。如果我使用像按钮这样的 asp 服务器控件,即使我将按钮用作服务器控件并将文本框用作普通 HTML 控件,我也不会从 ajax 调用中获得任何输出。提前致谢。

AjaxCall.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxCall.aspx.cs" Inherits="SampleLogin.AjaxCall" %>
<!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 runat="server">
    <title>Ajax Call</title>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
    // $('#<%= btnAjax.ClientID%>').click(function () {     // If i use this iam not getting any response
            $('#submit').click(function () {
                alert("clicked");
                $.ajax({
                    type: "POST",
                    url: "AjaxCall.aspx/HelloWorld",
                    data: "{}",
                    contentType: "application/json",
                    dataType: "json",
                    success: function (msg) {

                        alert(msg.d);
                        $("#Result").val(msg.d);
                    }
                });
            });
        });
  </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="click" id="submit"  />
        <asp:Button ID="btnAjax" runat="server" Text="GetVal" />
        <input type="text" ID="Result" runat="server">
    </div>
    </form>
</body>
</html>

AjaxCall.aspx.cs 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
namespace SampleLogin
{
    public partial class AjaxCall : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        [WebMethod(EnableSession = false)]
        public static string HelloWorld()
        {
            return "Hello";
        }
    }
}
4

2 回答 2

0

我使用了 preventDefault 功能,它现在对我有用

<script>
        $(document).ready(function () {
            $('#<%= btnAjax.ClientID %>').click(function (e) {
                alert("clicked e");
                e.preventDefault();

                $.ajax({
                    type: "POST",
                    url: "AjaxCall.aspx/HelloWorld",
                    data: "{}",
                    contentType: "application/json",
                    dataType: "json",
                    success: function (msg) {
                        // Replace the div's content with the page method's return.
                        alert(msg.d);
                        $("#<%=txtAjaxVal.ClientID %>").val(msg.d);
                    }
                });
            });
        });
  </script>
于 2013-06-25T07:35:08.310 回答
0

这是因为服务器端按钮导致页面回发到服务器...不确定为什么要使用服务器控件进行 ajax 调用?

于 2013-06-25T07:25:05.510 回答