Javascript

浏览模式: 标准 | 列表 | 图文
jQuery操作select

jQuery操作select

jQuery这个框架方便了我们对于HTML元素的操作,本来以为自己对于Select操作也算是熟悉了,但上午在测试的时候才发现自己了解的还真不多。

看了一下jQuery的一些方法后,理出了一些常用的方法,列在下面:

//获取第一个option的值
$('#test option:first').val();
//最后一个option的值
$('#test option:last').val();
//获取第二个option的值
$('#test option:eq(1)').val();
//获取选中的值
$('#test').val();
$('#test option:selected').val();
//设置值为2的option为选中状态
$('#test').attr('value','2');
//设置第一个option为选中
$('#test option:last').attr('selected','selected');
$("#test").attr('value' , $('#test option:last').val());
$("#test").attr('value' , $('#test option').eq($('#test option').length - 1).val());
//获取select的长度
$('#test option').length;
//添加一个option
$("#test").append("<option value='9'>ff</option>");
$("<option value='9'>ff</option>").appendTo("#test");
//添除选中项
$('#test option:selected').remove();
//指定项选中
$('#test option:first').remove();
//指定值被删除
$('#test option').each(function(){
if( $(this).val() == '5'){
$(this).remove();
}
});
$('#test option[value=5]').remove();

//获取第一个Group的标签
$('#test optgroup:eq(0)').attr('label');
//获取第二group下面第一个option的值
$('#test optgroup:eq(1) :option:eq(0)').val();

想来应该够用了吧?呵呵

孟宪会之AJAX(XMLHttpRequest)进行跨域请求方法详解

孟宪会之AJAX(XMLHttpRequest)进行跨域请求方法详解

孟宪会友情提醒:注意:以下代码请在Firefox 3.5、Chrome 3.0、Safari 4之后的版本中进行测试。IE8的实现方法与其他浏览不同。

跨域请求,顾名思义,就是一个站点中的资源去访问另外一个不同域名站点上的资源。这种情况很常见,比如说通过 style 标签加载外部样式表文件、通过 img 标签加载外部图片、通过 script 标签加载外部脚本文件、通过 Webfont 加载字体文件等等。默认情况下,脚本访问文档属性等数据采用的是同源策略(Same origin policy)。

那么,什么是同源策略呢?如果两个页面的协议、域名和端口是完全相同的,那么它们就是同源的。同源策略是为了防止从一个地址加载的文档或脚本访问或者设置 从另外一个地址加载的文档的属性。如果两个页面的主域名相同,则还可以通过设置 document.domain 属性将它们认为是同源的。

随着 Web2.0 和 SNS 的兴起,Web 应用对跨域访问的需求也越来越多,但是,在脚本中进行跨域请求是受安全性限制的,Web 开发人员迫切需要提供一种更安全、方便的跨域请求方式来融合(Mashup)自己的 Web 应用。这样做的一个好处就是可以将请求分摊到不同的服务器,减轻单个服务器压力以提高响应速度;另外一个好处是可以将不同的业务逻辑分布到不同的服务器上 以降低负载。

值得庆幸的是,跨域请求的标准已经出台,主流浏览器也已经实现了这一标准。W3C 工作组中的 Web Applications Working Group(Web 应用工作组)发布了一个 Cross-Origin Resource Sharing(跨域资源共享,该规范地址:http://www.w3.org/TR/access-control/和http: //dev.w3.org/2006/waf/access-control/) 推荐规范来解决跨域请求的问题。该规范提供了一种更安全的跨域数据交换方法。具体规范的介绍可以访问上面提供的网站地址。值得注意的是:该规范只能应用在 类似 XMLHttprequest 这样的 API 容器内。IE8、Firefox 3.5 及其以后的版本、Chrome浏览器、Safari 4 等已经实现了 Cross-Origin Resource Sharing 规范,已经可以进行跨域请求了。

Cross-Origin Resource Sharing 的工作方式是通过添加 HTTP 头的方法来判断哪些资源允许 Web 浏览器访问该域名下的信息。然而,对于那些 HTTP 请求导致用户数据产生副作用的请求方法(特别是对于除了GET、某些 MIME 类型的 POST 之外的 HTTP方法),该规范要求浏览器对请求进行“预先验”,通过发送 HTTP 的 OPTIONS 请求头询问服务器有哪些支持的方法,在征得服务器的同意后,再使用实际的 HTTP 请求方法发送实际的请求。服务器也可以通知客户端是否需要将验证信息(如 Cookie 和 HTTP Authentication 数据)随同请求一起发送。

下面我们就采用实际的例子说明 Cross-Origin Resource Sharing 是如何工作的。

1,简单请求

什么样的请求算是简单请求呢?简单请求必须满足下面2点:
a,只使用 GET、POST 进行的请求,这里的POST只包括发送给服务器的数据类型(Content-Type)必须是 application/x-www-form-urlencoded、multipart/form-data 或者 text/plain中一个。
b,HTTP 请求没有设置自定义的请求头,如我们常用的 X-JSON。

先使用下面的代码进行测试:

<!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>孟宪会之AJAX跨域请求测试</title>
</head>
<body>
<input type='button' value='开始测试' onclick='crossDomainRequest()' />
<div id="content"></div>
<mce:script type="text/javascript"><!--
var xhr = new XMLHttpRequest();
var url = 'http://dotnet.aspx.cc/SimpleCrossSiteRequests.aspx';
function crossDomainRequest() {
document.getElementById("content").innerHTML = "开始……";
if (xhr) {
xhr.open('GET', url, true);
xhr.onreadystatechange = handler;
xhr.send();
} else {
document.getElementById("content").innerHTML = "不能创建 XMLHttpRequest";
}
}
function handler(evtXHR) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = xhr.responseText;
document.getElementById("content").innerHTML = "结果:" + response;
} else {
document.getElementById("content").innerHTML = "不允许跨域请求。";
}
}
else {
document.getElementById("content").innerHTML += "<br/>执行状态 readyState:" + xhr.readyState;
}
}
// --></mce:script>
</body>
</html>

然后,在服务器创建 CrossDomainRequest.aspx 的内容如下:

<%@ Page Language="C#" %>
<mce:script runat="server"><!--
protected void Page_Load(object sender, EventArgs e)
{
Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
Response.Write("孟宪会向各位朋友发来贺电:你的第一个跨域测试成功啦!!!");
}
// --></mce:script>

点击 “开始测试” 按钮,发送的请求和返回的响应信息如下:

GET /SimpleCrossSiteRequests.aspx HTTP/1.1
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/SimpleCrossSiteRequests.html
Origin: http://www.meng_xian_hui.com:801
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 13:52:00 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Set-Cookie: ASP.NET_SessionId=wk5v5nrs5wbfi4rmpjy2jujb; path=/; HttpOnly
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 84

需要特别注意的是:在请求信息中,浏览器使用 Origin 这个 HTTP 头来标识该请求来自于 http://www.meng_xian_hui.com:801;在返回的响应信息中,使用 Access-Control-Allow-Origin 头来控制哪些域名的脚本可以访问该资源。如果设置 Access-Control-Allow-Origin:*,则允许所有域名的脚本访问该资源。如果有多个,则只需要使用逗号分隔开即可。

注意:在服务器端,Access-Control-Allow-Origin 响应头 http://www.meng_xian_hui.com:801 中的端口信息不能省略。

有人可能会想:自己发送请求头会如何呢?比如 xhr.setRequestHeader("Origin","http://www.meng_xian_hui.com:801"); 实践证明,自己设置 Origin 头是不行的。

是不是现在就可以采用 XMLHttpRequest 来请求任意一个网站的数据呢?还是不行的。允许哪些域名可以访问,还需要服务器来设置 Access-Control-Allow-Origin 头来进行授权,具体的代码是:

Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");

这行代码就告诉浏览器,只有来自 http://www.meng_xian_hui.com:801 源下的脚本才可以进行访问。

好了,上面我们就完成了一个简单的跨域请求,怎么样?感觉还是不错的吧。下面我们进行一个“预检”请求。

2,预检请求

预检请求首先需要向另外一个域名的资源发送一个 HTTP OPTIONS 请求头,其目的就是为了判断实际发送的请求是否是安全的。下面的2种情况需要进行预检:
a,不是上面的简单请求,比如使用Content-Type 为 application/xml 或 text/xml 的 POST 请求
b,在请求中设置自定义头,比如 X-JSON、X-MENGXIANHUI 等

注意:在 iis 里进行测试,必须在“应用程序扩展”里面配置 .aspx 扩展的动作允许 OPTIONS。

下面我们举一个预检的请求:

<!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>孟宪会之AJAX跨域请求测试</title>
</head>
<body>
<input type='button' value='开始测试' onclick='crossDomainRequest()' />
<div id="content"></div>
<mce:script type="text/javascript"><!--
var xhr = new XMLHttpRequest();
var url = 'http://dotnet.aspx.cc/PreflightedRequests.aspx';
function crossDomainRequest() {
document.getElementById("content").innerHTML = "开始进行请求……";
if (xhr) {
var xml = "<root>测试</root>";
xhr.open('POST', url, true);
xhr.setRequestHeader("POWERED-BY-MENGXIANHUI", "Approve");
xhr.setRequestHeader("Content-Type", "application/xml");
xhr.onreadystatechange = handler;
xhr.send(xml);
} else {
document.getElementById("content").innerHTML = "不能创建 XMLHttpRequest。";
}
}
function handler(evtXHR) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = xhr.responseText;
document.getElementById("content").innerHTML = "结果:" + response;
} else {
document.getElementById("content").innerHTML = "不能进行跨越访问。";
}
}
else {
document.getElementById("content").innerHTML += "<br/>执行状态 readyState:" + xhr.readyState;
}
}
// --></mce:script>
</body>
</html>

上面的例子我们发送 xml 格式的数据,并且,发送一个非标准的HTTP头 POWERED-BY-MENGXIANHUI 来说明服务器端该如何设置响应头的。

在服务器端,PreflightedRequests.aspx 的内容如下:

<%@ Page Language="C#" %>
<mce:script runat="server"><!--
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod.Equals("GET"))
{
Response.Write("这个页面是用来测试跨域 POST 请求的,直接浏览意义不大。");
}
else if (Request.HttpMethod.Equals("OPTIONS"))
{
//通知客户端允许预检请求。并设置缓存时间
Response.ClearContent();
Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
Response.AddHeader("Access-Control-Allow-Headers", "POWERED-BY-MENGXIANHUI");
Response.AddHeader("Access-Control-Max-Age", "30");
//此过程无需返回数据
Response.End();
}
else if (Request.HttpMethod.Equals("POST"))
{
if (Request.Headers["Origin"].Equals("http://www.meng_xian_hui.com:801"))
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(Request.InputStream);
Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
Response.Write("您提交的数据是:<br/><br/>" + Server.HtmlEncode(doc.OuterXml));
}
else
{
Response.Write("不允许你的网站请求。");
}
}
}
// --></mce:script>

点击“开始测试”按钮,将会执行下面的一系列请求。

OPTIONS /PreflightedRequests.aspx HTTP/1.1
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Origin: http://www.meng_xian_hui.com:801
Access-Control-Request-Method: POST
Access-Control-Request-Headers: powered-by-mengxianhui
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 14:00:34 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: POWERED-BY-MENGXIANHUI
Access-Control-Max-Age: 30
Set-Cookie: ASP.NET_SessionId=5npqri55dl1k1zvij1tlw3re; path=/; HttpOnly
Cache-Control: private
Content-Length: 0
POST /PreflightedRequests.aspx HTTP/1.1
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
POWERED-BY-MENGXIANHUI: Approve
Content-Type: application/xml; charset=UTF-8
Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html
Content-Length: 19
Origin: http://www.meng_xian_hui.com:801
Pragma: no-cache
Cache-Control: no-cache
<root>测试</root>
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 14:00:34 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Set-Cookie: ASP.NET_SessionId=byvose45zmtbqy45d2a1jf2i; path=/; HttpOnly
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 65

以上的代码反映了预检请求的执行过程:首先发送 OPTIONS 请求头,用来向服务器咨询服务器的更多信息,以便为后续的真实请求做准备。比如是否支持 POST 方法等。值得注意的是:

浏览器还发送 Access-Control-Request-Method: POST 和 Access-Control-Request-Headers: powered-by-mengxianhui 请求头。

注意:以上过程是第一次请求的时候的过程,如果在 30 秒内重复点击按钮,你可以看不到 OPTIONS 这一过程。则执行过程是这样的:

POST /PreflightedRequests.aspx HTTP/1.1
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
POWERED-BY-MENGXIANHUI: Approve
Content-Type: application/xml; charset=UTF-8
Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html
Content-Length: 19
Origin: http://www.meng_xian_hui.com:801
Pragma: no-cache
Cache-Control: no-cache
<root>测试</root>
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 14:06:32 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Set-Cookie: ASP.NET_SessionId=qs1c4urxywdbdx55u04pvual; path=/; HttpOnly
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 65

为什么会这样?细心的童鞋可能注意到了,在服务器端有一行代码 Response.AddHeader("Access-Control-Max-Age", "30"); 它是用来设置预检的有效时间的,单位是秒。这一点要特别注意。

3,带验证信息的请求

身份验证是Web开发中经常遇到的问题,在跨域请求中,默认情况下是不发送验证信息的。要想发送验证信息,需要进行withCredentials 属性,下面就是一个简单请求的例子:

<!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>孟宪会之AJAX跨域请求测试</title>
</head>
<body>
<input type='button' value='开始测试' onclick='crossDomainRequest()' />
<div id="content"></div>
<mce:script type="text/javascript"><!--
var xhr = new XMLHttpRequest();
var url = 'http://dotnet.aspx.cc/RequestsWithCredentials.aspx';
function crossDomainRequest() {
document.getElementById("content").innerHTML = "开始进行请求……";
if (xhr) {
xhr.open('GET', url, true);
xhr.onreadystatechange = handler;
xhr.withCredentials = "true";
xhr.send();
} else {
document.getElementById("content").innerHTML = "不能创建 XMLHttpRequest。";
}
}
function handler(evtXHR) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = xhr.responseText;
document.getElementById("content").innerHTML = "结果:" + response;
} else {
document.getElementById("content").innerHTML += "<br/>执行状态 status:" + xhr.status;
}
}
else {
document.getElementById("content").innerHTML += "<br/>执行状态 readyState:" + xhr.readyState;
}
}
// --></mce:script>
</body>
</html>

点击“开始测试”,我们可以检测到下面的请求执行过程:

GET /RequestsWithCredentials.aspx HTTP/1.1
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/RequestsWithCredentials.html
Origin: http://www.meng_xian_hui.com:801
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 14:12:26 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Access-Control-Allow-Credentials: true
Set-Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; path=/; HttpOnly
Set-Cookie: visit=1; expires=Sun, 10-Jan-2010 14:12:56 GMT; path=/
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: text/html; charset=utf-8
Content-Length: 1

从上面的响应中可以看出,Cookie 是会随请求一起发送的。如果我们多次点击测试按钮,则可以看到请求和响应的结果是这样的:

GET /RequestsWithCredentials.aspx HTTP/1.1
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/RequestsWithCredentials.html
Origin: http://www.meng_xian_hui.com:801
Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; visit=2
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 14:13:58 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Access-Control-Allow-Credentials: true
Set-Cookie: visit=3; expires=Sun, 10-Jan-2010 14:14:28 GMT; path=/
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: text/html; charset=utf-8
Content-Length: 1

注意 Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; visit=2 这一行,访问计数器已经被一起发送到服务器。

4,IE8 中的实现方法

IE8已经开始支持跨域访问资源了,但是,IE8提供的功能还比较简单,可以进行简单的请求,下面是一个使用的例子:

<!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>孟宪会之AJAX跨域请求测试</title>
</head>
<body>
<input type='button' value='开始测试' onclick='crossDomainRequest()' />
<div id="content"></div>
<mce:script type="text/javascript"><!--
var xhr = new XDomainRequest();
var url = 'http://dotnet.aspx.cc/SimpleCrossSiteRequests.aspx';
function crossDomainRequest() {
document.getElementById("content").innerHTML = "开始……";
if (xhr) {
xhr.open('GET', url);
xhr.onload = handler;
xhr.send();
} else {
document.getElementById("content").innerHTML = "不能创建 XDomainRequest";
}
}
function handler(evtXHR) {
document.getElementById("content").innerHTML = "结果:" + xhr.responseText;
}
// --></mce:script>
</body>
</html>

另外,IE8的实现方法与其他浏览器不同。更多内容请参考 XDomainRequest 对象,地址是:
http://msdn.microsoft.com/zh-cn/library/cc288060(VS.85).aspx

最后,愿意测试的朋友可以访问这个 http://dotnet.aspx.cc/SimpleCrossSiteRequests.aspx 地址进行“简单请求”的测试,本页面允许任何地址进行跨域访问。(不好意思,个人网站可能被河蟹了)

----EOF---

很长的文章,我把三篇并为一篇了。。如果嫌长,可以去这里查看 :

AJAX(XMLHttpRequest)进行跨域请求方法详解(一)

AJAX(XMLHttpRequest)进行跨域请求方法详解(二)

AJAX(XMLHttpRequest)进行跨域请求方法详解(三)

Ways to debug your jQuery or JavaScript codes

Ways to debug your jQuery or JavaScript codes

Debugging your client code is rather a normal procedures for any web developers. Everyone will shout Firebug! yeah, me too. But Firebug is great for syntax detection but how about logic problem? In this article i will share with you some of the ways i used to debug my JavaScript or jQuery codes when I’m developing my web application. I will also share with you a trick that i used on my code to alert me that a bug occurs in a particular script since i don’t get many helpful users nowadays.

Alert Them Out

The most simple and basic way of debugging is by using JavaScript alert function. This is old but is quite useful sometimes. Especially when you do not want to remember other debugging methods. It’s pretty simple, alert the message you want to see. If the alert doesn’t appear, this means that the error is before the alert statement. I usually do this when I’m debugging IE although there are tools available for IE.

alert("The Bug Is Somewhere Before ME!");

Log them up

Well, if you are using WebKit browsers for your development (FireFox, Chrome, Safari) you may want to try this.

if (window.console)
window.console.log("The Bug is killing me");

What this does is to log the string ‘The Bug is killing me’ into the console such as Firebug. It’s always better than using alert and see this infinity loop that keep popping out until you are force to shut down your browser!

Log them with jQuery

The above two methods work both in jQuery and JavaScript. But this only function well in jQuery. This is definitely not something i came up with but its from Dominic Mitchell

jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
};

The above creates a function, ‘log’. This function will do exactly similar to the one above but the differences is that it format the string a little bit before displaying out to the console. This is good for debugging your long chaining with jQuery. Although the previous method also can be used to debug chaining but it will required an additional line instead of including it into the chaining process. So you can debug this way,

$(root).find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");

Try and catch

In JavaScript, you can try to catch the error in a particular scope. This way, it won’t propagate to other section of the code.

try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}

This is pretty good when you are trying to debug one of the many function in your JavaScript.

Catch them all

The last one i am going to show you is to catch any one of the error into a particular function instead of using multiple try and catch.

function handleError(e)
{
alert(’An error has occurred!\n’+e);
return true;
}
window.onerror = handleError;

This will handle any error occurs in your JavaScript code to the function ‘handleError’. You will want to use this at the end of your script. Especially if you want to be informed whether a particular function or script has malfunction and the users are not reporting. Basically, what you can do is to gather all information and placed them into a String or JSON. Using ajax to delivery these information to your email or database. This way, your support team will have an idea which part are having problems and your system will be more reliable. (testing doesn’t means 100% bug free) The information that you may want to know are usually located at Navigator Object in JavaScript.

Summary

These are the methods i usually look at when debugging my own client script. It might not be everything but i hope it can be useful to some of you out there. Hope you learn something!

原文来自于:http://hungred.com/2009/08/04/useful-information/ways-debug-jquery-javascript-codes/

Author: Clay Lua

ExtJs 备忘录

ExtJs 备忘录

这个,当然不是我写的。我用的更多的应该是jQuery,相对于JS这方面来说,jQuery框架我用的是最多的。
在jQuery没有出来之前,用过一阵子的prototype,只是现在用的少了。
mootools是一点都没有碰过,dojo亦然。extJS和yui也同样只是稍看了一遍而己。为了ExtJS我还专门买了本书,只是却几乎没有翻过。

看到这个备忘录,就想着先收藏下来,留着以后慢慢看,这样也并不错啊。。。
这个系列一共九篇,讲了表单,表格和页面搭建,还是比较有用的。即使是初学者也可以迅速上手,当然如果不深究的话,终究只是于处应用阶段,属于知其然不知其所以然。。。

1.  ExtJs 备忘录(1)—— Form表单(一) [ 控件使用 ]
2.  ExtJs 备忘录(2)—— Form表单(二) [ 控件封装 ]
3.  ExtJs 备忘录(3)—— Form表单(三) [ 数据验证 ]
4.  ExtJs 备忘录(4)—— Form表单(四) [ 数据提交 ]
5.  ExtJs 备忘录(5)—— GirdPanl表格(一)[ 基本用法 ]
6.  ExtJs 备忘录(6)—— GirdPanl表格(二)[ 搜索分页 ]
7.  ExtJs 备忘录(7)—— GirdPanl表格(三)[ 统计|查看、修改单行记录 ]
8.  ExtJs 备忘录(8)—— 管理界面搭建和其他部分控件介绍
9.  ExtJs 备忘录(9)—— Ext常用属性、方法小结 [系列完]

随便看看吧。了解一下也好,毕竟熟悉了之后,用EXTJS做界面还是很漂亮的,当然,如果写的不好,内存吃起来也是很漂亮的。

如何去掉点击链接时周围的虚线框outline属性

如何去掉点击链接时周围的虚线框outline属性

找来找去,这个应该是最全的解决方案列表了。。突然间想找这个是因为,网易评论的“分页列表”用的是链接,但没有虚框,很好看,所以想找找这样的资料。。。

以下就属于原文了。。

如何隐藏掉点击链接时周围出现的虚线框呢?

在常规情况下,该虚线框是作为一种提示让用户明确当前关注的东西,然而如果我们把链接的4种状态样式设置比较完整的话,就不是特别需要虚线框的存 在,因为它很有可能影响页面的美观。尤其是在做应用系统界面的时候,总给人一种浏览网页的感觉,显得不够专业。我就遇到过这种情况,有次做一个WEB应用 项目,那用户以前使用桌面软件的,突然转到B/S软件下操作,老是觉得点击链接或按钮出现的虚线框让他很不爽。后来我们挨个把所有会出现虚线框的链接都改 过一遍,这客户高兴坏了,后来还说这系统功能性这么一改好用多了。可见,这么一个小小的东西,对用户体验是多么的重要。

当然,如果全盘否定掉链接虚线框,对使用键盘的用户体验可能又是个大弊端。但这就是另外一个话题了,这里就不说了,不然就扯出UI设计和用户体验这个大话题了,我这小小的地方可说不清楚呢。

以下是解决方案:

方法一:
在IE下是使用html属性:hideFoucs,在HTML标签中加上hidefocus=”true” 属性即可,但这个属性是IE私有的,Firefox是不认的。

<a href="#" hidefocus="true" title="加了hidefocus" >欢迎来到博客园(加了hidefocus属性)</a>
Firefox的处理方法比较符合标准,只需要在样式里设置a:focus{outline:none}皆可:
.xzw_test a.setFocus:focus{outline:none}

方法二:

通过javascript方法让其点击后失去焦点从而达到没有虚线框,也不失为一种曲线救国的方案:

//通过判断可以指定某个必要的链接失去焦点
if(j(this).attr("id")=="jsControl")
j(this).blur();

--EOF--

作者最后说:Opera也是很WEB标准的浏览器哦,大伙不妨多用用。

不过我现在已经不用了。中文版的opera太难看了。不知道UI是怎么设计的。又或者是我的字体有问题?还是我看惯FF或者safari?唉。。人被养刁了也不好。

由于我的页面不能提供测试样例,所以,想看测试样例的朋友还请移步到:http://www.cnblogs.com/miqi2214/archive/2008/12/25/1361996.html,里面有关于图片和链接的样例

jQuery1.4正式版发布

jQuery1.4正式版发布

每天看CB,总有新发现。这不,jQuery 1.4发布又是从他们网上看来的。每天多看评论总会找到一些新的乐趣。
比如,百度的一些关键词之类的。偶尔也能让自己为新奇的SEO方法找到一点窍门。

乱弹,乱弹,上主菜:

在jQuery的4岁生日之时,jQuery开发团队很高兴地发布最新的jQuery1.4版本!其他的代码演示、测试、文档的更新也会陆续进行更 新发 布。对于jQuery发烧友来说,jQuery1.4的发布也是一个大新闻!下面是来自于jQuery的官方网站翻译(英语高手请勿拍砖!): 在jQuery的4岁生日之时,jQuery开发团队很高兴地发布最新的jQuery1.4版本!其他的代码演示、测试、文档的更新也会陆续进行更新发 布。

jQuery Minified (23kb Gzipped)
jQuery Regular (154kb)

此外,谷歌已经提供了jQuery1.4副本,jquery团队上传到了Google服务器托管服务中。这jQuery1.4的版本是自动minified和gzip 的,地址为:
http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js

jquery1.4所有的变化和功能添加到jQuery1.4文档中。

--EOF--

看到jQuery又添加了这么多的新功能,实在为自己的行为感到惭愧,一直在用它,却从未为他做过贡献。

新闻来源:http://www.cnbeta.com/articles/102208.htm

命名函数表达式探秘

命名函数表达式探秘

应该来说,本文对于了解JS命名表达式有着非常重要的作用。就象文中说的:

简单来讲,命名函数表达式只有一个用处——在调试器或性能分析程序中描述函数的名称。没错,也可以使用函数名实现递归,但你很快就会知道,目前来看这通常是不切实际的。当然,如果你不关注调试,那就没什么可担心的。否则,就应该往下看一看,看看在跨浏览器开发中都会出现哪些小毛病(glitch),也看看应该怎样解决它们

所以,了解一下也算是挺不错的。再加上为之漫笔的翻译功底。。

不过,由于页面过长,我这里还是只贴一下列表就完事了。详细的内容请直接到为之漫笔的网上去看。当然,我是建议下载下来,毕竟就一个HTML文件。时不时的看看还是不错的啦 。

目录如下:

  1. 前言
  2. 函数表达式与函数声明
  3. 函数语句
  4. 命名函数表达式
  5. 调试器中的函数名
  6. JScript的bug
  7. JScript的内存管理
  8. 测试
  9. Safari中存在的bug
  10. SpiderMonkey的怪癖
  11. 解决方案
  12. 替代方案
  13. WebKit的displayName
  14. 对未来的思考
  15. 致谢
译者:为之漫笔

来源:http://www.cn-cuckoo.com/wordpress/wp-content/uploads/2009/12/named-function-expressions-demystified.html

记录,一个被我忘记三年多的变量

记录,一个被我忘记三年多的变量

designMode,这个被我遗忘三年的变量。连名都忘了。想了好久好久才想起来。。。

OK,设置这个变量为ON,那么页面上的元素就全可以编辑了,功能是用来干嘛的呢?好象有点忘了。当初是想用来直接COPY文章的。如今想起来,却不知道用来干嘛 了。

参考:

1、http://www.mozilla.org/editor/ie2midas.html

2、http://www.nirsoft.net/utils/ie_design_mode.html

jQuery插件:图片自动缩放

jQuery插件:图片自动缩放

同事需要,就写了个插件 。。。。
原来我也写过两个,但这次是正式为jQuery写的插件。。。

$(document).ready(function(){
$('div').autoResize({height:50});
});

jQuery.fn.autoResize = function(options)
{
var opts = {
'width' : 400,
'height': 300
}
var opt = $.extend(true, {},opts,options || {});
width = opt.width;
height = opt.height;
$('img',this).each(function(){
var image = new Image();
image.src = $(this).attr('src');
//开始检查图片
if(image.width > 0 && image.height > 0 ){
var image_rate = 1;
if( (width / image.width) < (height / image.height)){
image_rate = width / image.width ;
}else{
image_rate = height / image.height ;
}
if ( image_rate <= 1){
$(this).width(image.width * image_rate);
$(this).height(image.height * image_rate);
}
}
});
}

原来的两篇在这里:

jQuery1.4 Alpha 2发布

jQuery1.4 Alpha 2发布

作为一个jQuery的发烧友,对于jQuery1.4版本的新闻十分的关心,刚刚收到消息,jQuery1.4α2版本已经发布了。下面是我从 jQuery官方博客获得的消息: jQuery1.4 Alpha 2已经发布啦!这是jQuery1.4的第二个Alpha测试版本(第一版的发布链接),这个版本的代码是稳定的(并且在所有市面上流行的浏览器中通过了 测试) 获取jQuery1.4 α2版本:

未压缩版本:http://code.jquery.com/jquery-1.4a2.js
压缩版本:http://code.jquery.com/jquery-1.4a2.min.js

注意:如果您使用jQuery1.4 Alpha2版本,并且遇到了bug,请使用未压缩版本,它可以更加简单的找到错误的代码所在的位置。 目前所知道1.4版本的功能上相对版本 1.3.2进行了一些扩展,包括:

1.live 方法被大幅度检修,现在支持提交,更改,mouseenter,mouseleave,焦点,模糊在所有浏览器活动。现在还支持背景和数据。
2.append, prepend 方法优化
3.add has been adjusted to always return elements in document order.
4.find, empty, remove, addClass, removeClass, hasClass, attr, and css 等方法进行了重构,大大的优化

新闻来源:http://www.cnbeta.com/articles/100407.htm