AjaxTest.aspx:
<!--
注意使用1.6和1.7的版本的Jquery时调用远程Web Service失败,1.3和1.4的时候远程调用成功,所以调用1.4的版本
-->
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxTest.aspx.cs" Inherits="POCWBS.HTML5.AjaxTest" %>
<!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 id="Head1" runat="server">
<title>Templates</title>
<script type="text/html" id="personTemplate">
<div>
<div style="float:left;"> ID : </div> <div>${UId} </div>
<div style="float:left"> Name : </div> <div>${Name} </div>
<div style="float:left"> Address : </div> <div>${Address} </div> <br />
</div>
</script>
<!--<script src="../Js/jquery-1.7.2.min.js" type="text/javascript"></script>-->
<!--
jquery download address
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
-->
<script src="../Js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var personCount;
$(document).ready(function() {
PopulatePersons();
PopulateEmployees();
PopulateLocalServiceUsers();
PopulateRemoteServiceUsers();
CheckValidUser("487464","1");
});
function PopulatePersons(op) {
$.ajax({
type: "POST",
url: "AjaxTest.aspx/GetPersons",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: PersonAjaxSucceeded,
error: PersonAjaxFailed
});
}
function PersonAjaxSucceeded(result) {
alert('Person success');
//DisplayChildren(result);
}
function PersonAjaxFailed(result) {
alert('Person failure');
alert(result);
}
function DisplayChildren(result) {
var persons = eval(result.d);
personCount = persons.length;
$("#personTemplate").tmpl(persons).appendTo($("#divPerson"));
}
function AddPerson() {
var inputs = new Object();
inputs.count = ++personCount;
$.ajax({
type: "POST",
url: "AjaxTest.aspx/AddPerson",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(inputs),
dataType: "json",
success: PersonAjaxSucceeded,
error: PersonAjaxFailed
});
}
function PopulateEmployees() {
$.ajax({
type: "POST",
url: "AjaxLogic.aspx/GetEmployees",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: EmployeeAjaxSucceeded,
error: EmployeeAjaxFailed
});
}
function EmployeeAjaxSucceeded(result) {
alert('Employee success');
//DisplayChildren(result);
}
function EmployeeAjaxFailed(result) {
alert('Employee failure');
alert(result);
}
function PopulateLocalServiceUsers() {
$.ajax({
type: "POST",
url: "ajaxWebService.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: LocalUserAjaxSucceeded,
error: LocalUserAjaxFailed
});
}
function LocalUserAjaxSucceeded(result) {
alert('Local User success');
}
function LocalUserAjaxFailed(result) {
alert('Local User failure');
}
var WebServiceURL = "http://localhost/POCWBSWebService/";
function PopulateRemoteServiceUsers() {
$.ajax({
type: "POST",
url: WebServiceURL + "WebService1.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: RemoteUserAjaxSucceeded,
error: RemoteUserAjaxFailed
});
}
function RemoteUserAjaxSucceeded(result) {
alert('Remote User success');
}
function RemoteUserAjaxFailed(result) {
alert('Remote User failure');
}
function CheckValidUser(globalID,password)
{
// var inputs = new Object();
// inputs.globalID = globalID;
// inputs.password = password;
// $.ajax({
// type: "POST",
// url: "UserService.asmx/CheckValidUser",
// contentType: "application/json; charset=utf-8",
// data: JSON.stringify(inputs),
// dataType: "json",
// success: CheckUserAjaxSucceeded,
// error: CheckUserAjaxFailed
// });
// $.ajax({
// type: "POST",
// url: "UserService.asmx/CheckValidUser",
// contentType: "application/json; charset=utf-8",
// data:"{'globalID':'487464','password':'1'}",
// dataType: "json",
// success: CheckUserAjaxSucceeded,
// error: CheckUserAjaxFailed
// });
$.ajax({
type: "POST",
url: WebServiceURL + "UserService.asmx/CheckValidUser",
contentType: "application/json; charset=utf-8",
data:"{'globalID':'487464','password':'1'}",
dataType: "json",
success: CheckUserAjaxSucceeded,
error: CheckUserAjaxFailed
});
}
function CheckUserAjaxSucceeded(result)
{
alert('Check User success');
alert(result.d);
}
function CheckUserAjaxFailed(result)
{
alert('Check User failure');
alert(result.responseText);
alert(result.status);
alert(result.statusText);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<table>
<tr><td><input id="Button1" type="button" value="AddMorePerson" οnclick="AddPerson();"/></td></tr>
<tr><td>
<div id="divPerson" style="font-family:Verdana; font-size:12px;">
</div>
</td></tr>
</table>
<asp:HiddenField ID="hfPersonData" runat="server" />
</div>
</form>
</body>
</html>
AjaxTest.aspx.cs:
using System;
using System.Web.Services;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data.OleDb;
using System.Data;
namespace POCWBS.HTML5
{
public partial class AjaxTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod()]
public static string GetPersons()
{
List<Person> persons = new List<Person>()
{
new Person { UId = 1, Name = "Brij", Address = "Noida"},
new Person { UId = 2, Name = "Rahul", Address = "New Delhi" },
new Person { UId = 3, Name = "John0", Address = "Chris"}
};
JavaScriptSerializer ser = new JavaScriptSerializer();
// ser.Serialize(persons);
return ser.Serialize(persons);
}
[WebMethod()]
public static string AddPerson(string count)
{
List<Person> persons = new List<Person>()
{
new Person() { UId = Convert.ToInt32(count), Name = "New Name" + count, Address = "My New Address" + count }
};
JavaScriptSerializer ser = new JavaScriptSerializer();
// ser.Serialize(persons);
return ser.Serialize(persons);
}
}
public class Person
{
public int UId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
}
本地工程页面文件 AjaxLogic.aspx.cs
using System;
using System.Web.Services;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace POCWBS.HTML5
{
public partial class AjaxLogic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod()]
public static string GetEmployees()
{
List<Employee> persons = new List<Employee>()
{
new Employee { EmployeeId = 1000, Age=34, Name ="Rahul",
Adresses = new List<Address>()},
new Employee { EmployeeId = 1001, Age=29, Name ="Atul",
Adresses = new List<Address>()},
new Employee { EmployeeId = 1002, Age=32, Name ="Rohan",
Adresses = new List<Address>()}
};
persons[0].Adresses.Add(new Address() { Street = "Street 5", AddressLine1 = "New Bay Area", AddressLine2 = "Near Roma Hospital", City = "Kolkata", Zip = "221001" });
persons[0].Adresses.Add(new Address() { Street = "Bahadur marg", AddressLine1 = "Kailash Colony", AddressLine2 = "Near Public School", City = "Lucknow", Zip = "226001" });
persons[0].Adresses.Add(new Address() { Street = "Ali Crossing", AddressLine1 = "Republic Colony", AddressLine2 = "Silk Garden", City = "Ahamedabad", Zip = "221021" });
persons[1].Adresses.Add(new Address() { Street = "Street No 2", AddressLine1 = "Pocket Gama", AddressLine2 = "Near Appollo Hospital", City = "G Noida", Zip = "201301" });
persons[1].Adresses.Add(new Address() { Street = "1634", AddressLine1 = "Sector 15", AddressLine2 = "Near Nirulas", City = "Noida", Zip = "201301" });
persons[2].Adresses.Add(new Address() { Street = "Street 10", AddressLine1 = "Sector 18", AddressLine2 = "Near Mosaic", City = "Noida", Zip = "201301" });
persons[2].Adresses.Add(new Address() { Street = "Gol Marg", AddressLine1 = "New Era Colony", AddressLine2 = "Pitambaram", City = "Alllahabad", Zip = "221001" });
JavaScriptSerializer ser = new JavaScriptSerializer();
// ser.Serialize(persons);
return ser.Serialize(persons);
}
}
public class Employee
{
public int EmployeeId { get; set; }
public String Name { get; set; }
public int Age { get; set; }
public List<Address> Adresses { get; set; }
}
public class Address
{
public string Street { get; set; }
public String AddressLine1 { get; set; }
public String AddressLine2 { get; set; }
public string City { get; set; }
public string Zip { get; set; }
}
}
本工程内的Web Service 文件ajaxWebService.asmx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace POCWBS.HTML5
{
/// <summary>
/// Summary description for ajaxWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ajaxWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod()]
public string GetUsers()
{
List<User> users = new List<User>()
{
new User { UId = 1, Name = "Brij", Address = "Noida"},
new User { UId = 2, Name = "Rahul", Address = "New Delhi" },
new User { UId = 3, Name = "John0", Address = "Chris"}
};
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(users);
}
}
public class User
{
public int UId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
}
其他工程的Web Service文件 UserService.asmx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Text;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace POCWBSWebService
{
/// <summary>
/// Summary description for UserService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class UserService : System.Web.Services.WebService
{
[WebMethod]
public string CheckValidUser(string globalID, string password)
{
//string sql = "select * from Customers";
//Database db = DatabaseFactory.CreateDatabase();
//DataSet ds = db.ExecuteDataSet(CommandType.Text, sql);
//return ds;
string _strMsg = "";
string _strPath = Server.MapPath("Files/Users.xls");
try
{
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + _strPath + ";" +
"Extended Properties='Excel 8.0;IMEX=1;'";
string sql = "select * from [Sheet1$] WHERE [GLOBAL_ID]='" + globalID + "' and [PASSWORD]='" + password + "'";
OleDbCommand cmd = new OleDbCommand(sql, new OleDbConnection(conn));
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
_strMsg = "succ";
}
else
{
_strMsg = "User does not exist or password is not correct.";
}
}
catch (Exception ex)
{
_strMsg = "Exception:" + ex.Message.ToString();
}
return _strMsg;
}
[WebMethod]
public string GetDatas(String PA, String PB)
{
//return DataTable2Json(CreateDatas(PA, PB));
return string.Format("{0}、{1}", PA, PB);
}
//for test
private System.Data.DataTable CreateDatas(String PA, String PB)
{
System.Data.DataTable DT = new System.Data.DataTable("BlogUser");
System.Data.DataRow dr;
DT.Columns.Add(new System.Data.DataColumn("UserId", typeof(System.Int32)));
DT.Columns.Add(new System.Data.DataColumn("UserName", typeof(System.String)));
DT.PrimaryKey = new System.Data.DataColumn[] { DT.Columns["UserId"] };
for (int i = 0; i < 8; i++)
{
dr = DT.NewRow();
dr[0] = i;
dr[1] = "【孟子E章】" + i.ToString() + " 前端传递的参数的值分别是:" + PA + ", " + PB;
DT.Rows.Add(dr);
}
return DT;
}
private string DataTable2Json(System.Data.DataTable dt)
{
StringBuilder TB = new StringBuilder();
TB.Append("{\"");
TB.Append(dt.TableName.ToString());
TB.Append("\":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
TB.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
TB.Append("\"");
TB.Append(dt.Columns[j].ColumnName);
TB.Append("\":\"");
TB.Append(dt.Rows[i][j].ToString());
TB.Append("\",");
}
TB.Remove(TB.Length - 1, 1);
TB.Append("},");
}
TB.Remove(TB.Length - 1, 1);
TB.Append("]");
TB.Append("}");
return TB.ToString();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod()]
public string GetUsers()
{
List<User> users = new List<User>()
{
new User { UId = 1, Name = "Brij", Address = "Noida"},
new User { UId = 2, Name = "Rahul", Address = "New Delhi" },
new User { UId = 3, Name = "John0", Address = "Chris"}
};
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(users);
}
}
public class User
{
public int UId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
}