最终,我想通过点击按钮向服务器发送一个值并查询我的数据库。现在,我在使用jquery.ajax调用服务器端的函数时遇到了麻烦。这是我的代码:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ajax.aspx.cs" Inherits="WebApplication1.ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="/Scripts/jquery-1.6.2.min.js"></script>
<script language="Javascript" type="text/javascript">
if (jQuery) { alert("jQuery loaded"); }
function send()
{
$.ajax(
{
type: "get",
url: "ajax.aspx/Test",
data: { name: 'ok' },
success: function (result) { alert("successful!"); }
})
}
</script>
<input type="button" runat="server" value="TryMe" onclick="send()" />
</asp:Content>
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string Test(string sendData)
{
return String.Format("Hello {0}", sendData);
}
答案 0 :(得分:5)
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/此链接可能很有用
编辑:您的ajax调用必须如下所示: $.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax.aspx/Test",
data: "{ sendData: 'ok' }",
success: function (result) { alert("successful!"); }
})
答案 1 :(得分:1)
有几件事情不太正确:
完整示例:
function send() {
$.ajax({
type: "POST",
url: "ajax.aspx/Test",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
});
}
此代码适用于我。