在下面提到的代码中,只有当我使用 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";
}
}
}