在下面提到的代码中,只有在我使用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";
}
}
}
答案 0 :(得分:0)
这是因为服务器端按钮会导致页面回发到服务器...不确定为什么要使用服务器控件进行ajax调用?
答案 1 :(得分: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>