aspx页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Data.aspx.cs" Inherits="Data" %> <!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></title> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> //1,jquer方式调用asp.net后台方法 $(function () { $("#getuser").click(function () { $.ajax({ type:"post", contentType:"application/json;utf-8", datatype:"json", url:"data.aspx/GetUser", data:"{}", success:function(data){ var obj=eval("("+data.d+")"); alert('姓名:'+obj.name+'年龄:'+obj.age); }, error:function(err){ alert(err); } }); }); }); //2.原始ajax方式调用asp.net后台方法 //创建xmlHttp对象 var xmlHttpReq; function createXMLHttp() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlHttpReq = new XMLHttpRequest(); } else { //code for IE5, IE6 xmlHttpReq = new ActiveXObject("Microsoft.XMLHttp"); } } //创建请求函数 function ajaxRequest(url) { createXMLHttp(); xmlHttpReq.open('POST', url, false); xmlHttpReq.setRequestHeader("Content-type", "application/json"); xmlHttpReq.onreadystatechange = callBack; xmlHttpReq.send(null); } //创建回调函数 function callBack() { if (xmlHttpReq.readyState == 4) { alert(xmlHttpReq.readyState); if (xmlHttpReq.status == 200) { var res = xmlHttpReq.responseText; //res="{"d":"{name:\u0027puter\u0027,age:33}"}" ;
var obj=eval("("+res+")"); //obj.d="{name:'puter',age:33}";
var user=eval("("+obj.d+")"); //user={name:'puter',age:33}
alert("姓名:"+user.name+",年龄:"+user.age); } } } function send() { var url = "Data.aspx/GetUser"; ajaxRequest(url); } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" id="getuser" value="获得用户" /> <input type="button" id="oldajax" value="oldajax" onclick="send()"/> </div> </form> </body> </html>
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Script.Services; using System.Web.Services; public partial class Data : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string GetUser() { return "{name:'puter',age:33}"; //return "sssssssss"; } }