在上一篇文章<<ExtJs+WCF+LINQ实现分页Grid>>中用ExtJs与Wcf交互实现了分页Grid,回复中心有灵犀同学希望能采用跨域访问的方式,这个问题其实也困扰了我很久,本来ExtJS用ScriptTagProxy支持跨域访问的,如果服务端是.aspx的页面文件,也非常好实现,但换作WCF,问题就复杂起来。本文尝试解决这个问题,方案不是很巧妙,但是我对多种方案实验中第一个且是唯一有效的办法。
首先看一下如何用ExtJs中的ScriptTagProxy跨域访问服务器.aspx页面,不是重点,但与为何此种方法不适用WCF相关,所以也赘述下,项目是上文中的项目,下面是实现步骤:
第一步:还是向网站中添加Service.aspx页面,然后将其代码更改如下:
Service.aspx代码
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace ExtJs_Wcf_Linq_PageGrid
{
public partial class Service : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int start = Convert.ToInt32(Request.QueryString["start"]);
int limit = Convert.ToInt32(Request.QueryString["limit"]);
string callback = Request.QueryString["callback"];
ProductsDataContext productDbContext = new ProductsDataContext();
IQueryable<Product> res = productDbContext.Product.Select(product => product);
PageData<Product[]> returnData = new PageData<Product[]>();
returnData.TotolRecord = res.ToArray<Product>().Length;
res = res.Skip<Product>(start);
res = res.Take<Product>(limit);
returnData.Data = res.ToArray<Product>();
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PageData<Product[]>));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, returnData);
ms.Position = 0;
System.IO.StreamReader sr = new System.IO.StreamReader(ms);
Response.Write(callback+"("+sr.ReadToEnd()+")");
}
}
}
}
第二步:创建一个htm页面PageGridCrossDomain.htm,然后将其代码更改为:
PageGridCrossDomain.htm
<!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>
<title>ExtJs+WCF+LINQ打造分页Grid</title>
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css" />
<script type="text/javascript" src="adapter/ext/ext-base.js" charset="gb2312"></script>
<script type="text/javascript" src="ext-all-debug.js" charset="gb2312"></script>
<link rel="stylesheet" type="text/css" href="shared/examples.css" />
<script type="text/javascript" src="shared/examples.js" charset="gb2312"></script>
<script src="ScriptTagReader.js" type="text/javascript"></script>
<script type="text/javascript" src="PageCrossDomain.js" charset="gb2312"></script>
</head>
<body>
<h1>
ExtJs+WCF+LINQ打造分页跨域Grid</h1>
<div id="page-grid">
</div>
</body>
</html>