顯示具有 JavaScript 標籤的文章。 顯示所有文章
顯示具有 JavaScript 標籤的文章。 顯示所有文章
2023-03-14 13:23

[ThreeJS] 噴水粒子

要完成這個效果有三個問題要解決

  1. 自然的粒子分布
  2. 粒子的拋物線移動
  3. 粒子的擴散效果

我採用簡單的方式達成

  1. 用亂數產生分段的粒子團
  2. 用二次貝茲曲線建立拋物線
  3. 用粒子團的放大產生擴散效果

因為我用簡單的亂數分布粒子,粒子團會有立方體現象,球體分布會更好,但多個區段連起來就不明顯了。

二次貝茲曲線最大的困難在計算出結尾座標的位置,透過轉換到世界空間去定位出平面高度的座標,再轉換回物體空間來計算出結尾座標。

動畫用 AnimationMixer 去控制,只要定出每段粒子團的開始播放時間,粒子團就會接續的移動。

circle.png

程式:

/* 初始化渲染器 */
const renderer = new THREE.WebGLRenderer({ antialias: true });
document.getElementById('Container').appendChild(renderer.domElement);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

/* 初始化場景 */
const scene = new THREE.Scene();
scene.background = new THREE.Color('#111'); /* 背景顏色 */
scene.add(new THREE.AmbientLight('#FFF', 0.5)); /* 加入環境光 */

/* 地面 */
const floorMesh = new THREE.Mesh(
    new THREE.PlaneGeometry(200, 200),
    new THREE.MeshBasicMaterial({ color: '#DDD', depthWrite: false })
);
floorMesh.rotation.x = THREE.MathUtils.degToRad(-90);
scene.add(floorMesh);


/* 初始化鏡頭 */
const camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.1, 300);
camera.position.set(0, 10, 22);

/* 初始化軌道控制,鏡頭的移動 */
const orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
orbitControls.update();


/* 動畫刷新器 */
const mixers = [];

function newMixer(target) {
    const mixer = new THREE.AnimationMixer(target);
    mixers.push(mixer);
    return mixer;
}

/* 動畫計時器 */
const clock = new THREE.Clock();

/* 渲染週期 */
function renderCycle() {
    const delta = clock.getDelta();
    mixers.forEach(x => x.update(delta));

    renderer.render(scene, camera);
    requestAnimationFrame(renderCycle);
}
renderCycle();



/*---------------------------------------------------------------*/

/* 水管物件,水滴粒子群組會附加在這裡 */
const pipeMesh = new THREE.Mesh(
    new THREE.CylinderGeometry(0.5, 0.5, 9, 16),
    new THREE.MeshBasicMaterial( {color: '#eea236'} )
);
pipeMesh.rotation.x = THREE.MathUtils.degToRad(0);
pipeMesh.position.set(0, 4, 0);
scene.add(pipeMesh);


const dripGroup = new THREE.Group();
dripGroup.position.set(0, 4, 0);
pipeMesh.add(dripGroup);


/* 水滴材質 */
const dripMaterial = new THREE.PointsMaterial({
    map: new THREE.TextureLoader().load('circle.png'),
    color: '#0aa',
    size: 1,
    opacity: 0.7,
    depthWrite: false,
    transparent: true,
});


/* 建立水滴,用亂數建立粒子點 */
for (let i = 0; i < 60; i++) {
    const vertices = [];

    for (let j = 0; j < 40; j++) {
        const x = Math.random() - 0.5;
        const y = Math.random() - 0.5;
        const z = Math.random() - 0.5;
        vertices.push(x, y, z);
    }

    const geometry = new THREE.BufferGeometry();
    geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));

    const particles = new THREE.Points(geometry, dripMaterial);
    dripGroup.add(particles);

    newMixer(particles); /* 水滴動畫 */
}


/*---------------------------------------------------------------*/

const cycle = 2; /* 循環週期,會影響水流速度 */
const scale = 8; /* 擴散大小 */
const length = 14; /* 水流長度 */


/* 二次貝茲曲線,用來取得拋物線的座標點 */
const curve = new THREE.QuadraticBezierCurve3();
curve.v1.set(0, length, 0); /* 曲線控制點座標 */


/* 計算結尾座標 */
const rootPos = dripGroup.getWorldPosition(new THREE.Vector3());
const quaternion = dripGroup.getWorldQuaternion(new THREE.Quaternion());
const toPos = curve.v1.clone();
toPos.applyQuaternion(quaternion); /* 轉換到世界空間 */

/* 當水流是向上時,增加平面位置 */
if (toPos.y > (length / 3)) {
    toPos.x *= 1.8;
    toPos.z *= 1.8;
}
toPos.y = Math.min(-rootPos.y, toPos.y * 1.5); /* 將結尾拉回平面高度 */
toPos.applyQuaternion(quaternion.conjugate()); /* 轉換回物體空間 */
curve.v2.copy(toPos); /* 曲線結尾點座標 */


/* 建立拋物線及擴散動畫 */
const points = curve.getPoints(10); /* 曲线分段 */

const curveTime = [];
const curvePos = [];
points.forEach((v, i) => {
    curveTime.push(cycle * i / points.length);
    curvePos.push(v.x, v.y, v.z);
});
const posTrack = new THREE.VectorKeyframeTrack('.position', curveTime, curvePos);
const scaleTrack = new THREE.VectorKeyframeTrack('.scale', [0, cycle], [0, 0, 0, scale, scale, scale]);
const clip = new THREE.AnimationClip('scale', cycle, [posTrack, scaleTrack]);

mixers.forEach((mixer, i) => {
    const action = mixer.clipAction(clip);
    action.time = cycle * i / mixers.length;
    action.play();
});
2023-03-07 16:55

[ThreeJS] 單次動畫

/* 單次動畫 */
function animateOnce(mixer, prop, dur, values) {
    /* 停止 & 清除 先前的動畫 */
    mixer.stopAllAction();
    mixer.uncacheRoot(mixer.getRoot());

    /* 增加動畫片段 */
    const track = new THREE.KeyframeTrack(prop, [0, dur], values);
    const clip = new THREE.AnimationClip('move', dur, [track]);
    const action = mixer.clipAction(clip);
    action.clampWhenFinished = true;
    action.setLoop(THREE.LoopOnce);

    /* Promise 來處理完成事件,這樣就可以用 await */
    return new Promise((resolve) => {
        const finished = function () {
            mixer.removeEventListener('finished', finished);
            resolve();
        };
        mixer.addEventListener('finished', finished);

        action.play(); /* 播放動畫 */
    });
}

想要能像 SVG 一樣簡單的控制模型的移動,ThreeJS 並沒有直接提供我想要的模式,試了很久終於成功了。

mixer 中的 action 是不斷添加的,這會混亂播放動畫,所以在播放新的動畫前必須[停止]且[清除]先前的動畫。

為了可以簡單串接不同模型的動畫,所以就想用 await 來達成,所以加上 Promise 的包裝。

完整程式

/* 初始化渲染器 */
const renderer = new THREE.WebGLRenderer({ antialias: true });
document.getElementById('Container').appendChild(renderer.domElement);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

/* 初始化場景 */
const scene = new THREE.Scene();
scene.background = new THREE.Color('#000'); /* 背景顏色 */
scene.add(new THREE.AmbientLight('#FFF', 0.5)); /* 加入環境光 */
scene.add(new THREE.AxesHelper(50)); /* 3D 軸標示 */

/* 初始化鏡頭 */
const camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.1, 300);
camera.position.set(0, 4, 12);

/* 初始化軌道控制,鏡頭的移動 */
const orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
orbitControls.update();


/* 動畫刷新器 */
const mixers = [];

function newMixer(target) {
    const mixer = new THREE.AnimationMixer(target);
    mixers.push(mixer);
    return mixer;
}

/* 動畫計時器 */
const clock = new THREE.Clock();

/* 渲染週期 */
function renderCycle() {
    const delta = clock.getDelta();
    mixers.forEach(x => x.update(delta));

    renderer.render(scene, camera);
    requestAnimationFrame(renderCycle);
}
renderCycle();



/*---------------------------------------------------------------*/

/* 單次動畫 */
function animateOnce(mixer, prop, dur, values) {
    /* 停止 & 清除 先前的動畫 */
    mixer.stopAllAction();
    mixer.uncacheRoot(mixer.getRoot());

    /* 增加動畫片段 */
    const track = new THREE.KeyframeTrack(prop, [0, dur], values);
    const clip = new THREE.AnimationClip('move', dur, [track]);
    const action = mixer.clipAction(clip);
    action.clampWhenFinished = true;
    action.setLoop(THREE.LoopOnce);

    /* Promise 來處理完成事件,這樣就可以用 await */
    return new Promise((resolve) => {
        const finished = function () {
            mixer.removeEventListener('finished', finished);
            resolve();
        };
        mixer.addEventListener('finished', finished);

        action.play(); /* 播放動畫 */
    });
}


const cubeA = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial( {color: '#0F0'} )
);
const mixerA = newMixer(cubeA);
scene.add(cubeA);


const cubeB = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial( {color: '#00F'} )
);
const mixerB = newMixer(cubeB);
scene.add(cubeB);


async function run() {
    await animateOnce(mixerA, '.position[x]', 3, [0, 3]);
    await animateOnce(mixerB, '.position[y]', 3, [0, 2]);
    await animateOnce(mixerA, '.position[x]', 3, [3, 0]);
    await animateOnce(mixerB, '.position[y]', 3, [2, 0]);
}

run();
2023-03-07 16:06

[ThreeJS] 用 SVG 貼圖顯示中文

HTML

<div id="Container"></div>

<div id="LabelTpl" style="display:none;">
    <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 30 30">
        <text x="15" y="15" fill="#fff" text-anchor="middle"></text>
    </svg>
</div>

<script src="../Scripts/three.145/three.min.js"></script>
<script src="../Scripts/three.145/controls/OrbitControls.js"></script>
<script src="../Scripts/three.145/loaders/GLTFLoader.js"></script>
<script src="main.js"></script>

main.js

/* 初始化渲染器 */
const renderer = new THREE.WebGLRenderer({ antialias: true });
document.getElementById('Container').appendChild(renderer.domElement);

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);


/* 初始化場景 */
const scene = new THREE.Scene();
scene.background = new THREE.Color('#000'); /* 背景顏色 */
scene.add(new THREE.AmbientLight('#FFF', 0.5)); /* 加入環境光 */
scene.add(new THREE.AxesHelper(50)); /* 3D 軸標示 */

/* 初始化鏡頭 */
const camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.1, 300);
camera.position.set(0, 4, 12);


/* 初始化軌道控制,鏡頭的移動 */
const orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
orbitControls.update();


/* 渲染週期 */
function renderCycle() {
    renderer.render(scene, camera);
    requestAnimationFrame(renderCycle);
}
renderCycle();



/*---------------------------------------------------------------*/

function svgBase64(svg) {
    svg = svg.replace(/\s+</g, '<').replace(/>\s+/g, '>');
    return 'data:image/svg+xml,' + encodeURIComponent(svg);
}


const textureLoader = new THREE.TextureLoader();
const $labelTpl = document.querySelector('#LabelTpl');
const $labelText = document.querySelector('#LabelTpl text');


/* 環線 */
function addCircle(label,  z) {
    $labelText.innerHTML = label;
    let imageData = svgBase64($labelTpl.innerHTML);

    const particles = new THREE.Points(
        new THREE.EdgesGeometry(new THREE.CircleGeometry(10, 6)),
        new THREE.PointsMaterial({
            map: textureLoader.load(imageData),
            color: '#FFF',
            size: 4,
            depthWrite: false,
            transparent: true,
        })
    );
    particles.position.z = z;
    scene.add(particles);


    const circle = new THREE.LineSegments(
        new THREE.EdgesGeometry(new THREE.CircleGeometry(10, 60)),
        new THREE.LineBasicMaterial({ color: '#FFF' })
    );
    circle.position.z = z;
    scene.add(circle);
}

addCircle('冬至', 4);
addCircle('夏至', -4);
2023-03-07 13:01

[ThreeJS] 解決陰影造成的條紋

 會出現條紋現象是因為雙面材質,只要設置為單面材質就可以解決。

/* 載入模型 */
new THREE.GLTFLoader().load('Model.glb', function (gltf) {
    const model = gltf.scene;

    model.traverse(obj => {
        if (!obj.isMesh) { return; }

        obj.frustumCulled = false;
        obj.castShadow = true;
        obj.receiveShadow = true;

        /* 解決陰影造成的條紋 */
        obj.material.side = THREE.FrontSide;
        obj.material.shadowSide = THREE.FrontSide;
    });

    scene.add(model);
});
2023-03-07 11:37

[ThreeJS] 載入壓縮過 GLTF 檔

/* 解壓縮 lib 載入器
 * https://threejs.org/docs/#examples/en/loaders/DRACOLoader
 * https://google.github.io/draco/
 */
const dracoLoader = new THREE.DRACOLoader();

/* 指定解壓器的位置 */
dracoLoader.setDecoderPath('../Scripts/three.145/libs/draco/');


/* GLTF 載入器 */
const gltfLoader = new THREE.GLTFLoader();
gltfLoader.setDRACOLoader(dracoLoader);

/* 載入模型 */
gltfLoader.load('Model.glb', function (gltf) {
    const model = gltf.scene;
    scene.add(model);
});
2022-09-05 11:29

[轉載] opencv js getPerspectiveTransform,perspectiveTransform 方法使用

轉載自: opencvjs getPerspectiveTransform,perspectiveTransform方法使用

OpenCV JavaScript版本,使用getPerspectiveTransform,PerspectiveTransform方法。

JavaScript和python版本不同的是Mat的创建方法不同,python会在内部自动把数据转换成Mat类,也JavaScript不会,所以刚开始没有找到JavaScript创建Mat方法,走了很多弯路。

这只是测试代码,没有使用项目中真实的数据,所有有一定的偏差。

如果有什么错误,欢迎纠正。

下面上代码:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Hello OpenCV.js</title>
</head>

<body>
  <h2>Hello OpenCV.js</h2>
  <h2>getPerspectiveTransform,PerspectiveTransform方法使用</h2>
  <p id="status">OpenCV.js is loading...</p>
  <div>
    <button onClick="myclick()">输出结果</button>
  </div>
  <script type="text/javascript">
    function myclick() {
      //代码 getPerspectiveTransform
      //创建数据
      let srcTri = cv.matFromArray(4, 1, cv.CV_32FC2, [56, 65, 368, 52, 28, 387, 389, 390]);
      let dstTri = cv.matFromArray(4, 1, cv.CV_32FC2, [0, 0, 300, 0, 0, 300, 300, 300]);
      //转换的数据
      let M = cv.getPerspectiveTransform(srcTri, dstTri);
      console.log("getPerspectiveTransform M", M);

      //==== PerspectiveTransform ======
      //point点的数据一定要是一维的,opencv会自己去处理
      let points = [
        1, 2,
        3, 4,
        5, 6,
        7, 8
      ];
      //原数据
      points = cv.matFromArray(4,1,cv.CV_32FC2,points);
      //转换后的数据
      let points_trans = new cv.Mat();
      cv.perspectiveTransform(points, points_trans,M);
      console.log("points", points);
      console.log("points_trans", points_trans);

    }
    function onOpenCvReady() {
      document.getElementById('status').innerHTML = 'OpenCV.js is ready.';

    }
  </script>
  <script async src="https://docs.opencv.org/4.x/opencv.js" onload="onOpenCvReady();" type="text/javascript"></script>
  <script src="https://docs.opencv.org/4.x/utils.js" type="text/javascript"></script>
</body>

</html>

getPerspectiveTransform结果

perspectiveTransform结果

2022-07-15 12:38

[轉載] CSS 变量教程

轉載自:阮一峰 CSS 变量教程

今年三月,微软宣布 Edge 浏览器将支持 CSS 变量。

这个重要的 CSS 新功能,所有主要浏览器已经都支持了。本文全面介绍如何使用它,你会发现原生 CSS 从此变得异常强大。

一、变量的声明

声明变量的时候,变量名前面要加两根连词线(--)。

body {
  --foo: #7F583F;
  --bar: #F7EFD2;
}

上面代码中,body选择器里面声明了两个变量:--foo--bar

它们与colorfont-size等正式属性没有什么不同,只是没有默认含义。所以 CSS 变量(CSS variable)又叫做"CSS 自定义属性"(CSS custom properties)。因为变量与自定义的 CSS 属性其实是一回事。

你可能会问,为什么选择两根连词线(--)表示变量?因为$foo被 Sass 用掉了,@foo被 Less 用掉了。为了不产生冲突,官方的 CSS 变量就改用两根连词线了。

各种值都可以放入 CSS 变量。

:root{
  --main-color: #4d4e53;
  --main-bg: rgb(255, 255, 255);
  --logo-border-color: rebeccapurple;

  --header-height: 68px;
  --content-padding: 10px 20px;

  --base-line-height: 1.428571429;
  --transition-duration: .35s;
  --external-link: "external link";
  --margin-top: calc(2vh + 20px);
}

变量名大小写敏感,--header-color--Header-Color是两个不同变量。

二、var() 函数

var()函数用于读取变量。

a {
  color: var(--foo);
  text-decoration-color: var(--bar);
}

var()函数还可以使用第二个参数,表示变量的默认值。如果该变量不存在,就会使用这个默认值。

color: var(--foo, #7F583F);

第二个参数不处理内部的逗号或空格,都视作参数的一部分。

var(--font-stack, "Roboto", "Helvetica");
var(--pad, 10px 15px 20px);

var()函数还可以用在变量的声明。

:root {
  --primary-color: red;
  --logo-text: var(--primary-color);
}

注意,变量值只能用作属性值,不能用作属性名。

.foo {
  --side: margin-top;
  /* 无效 */
  var(--side): 20px;
}

上面代码中,变量--side用作属性名,这是无效的。

三、变量值的类型

如果变量值是一个字符串,可以与其他字符串拼接。

--bar: 'hello';
--foo: var(--bar)' world';

利用这一点,可以 debug(例子)。

body:after {
  content: '--screen-category : 'var(--screen-category);
}

如果变量值是数值,不能与数值单位直接连用。

.foo {
  --gap: 20;
  /* 无效 */
  margin-top: var(--gap)px;
}

上面代码中,数值与单位直接写在一起,这是无效的。必须使用calc()函数,将它们连接。

.foo {
  --gap: 20;
  margin-top: calc(var(--gap) * 1px);
}

如果变量值带有单位,就不能写成字符串。

/* 无效 */
.foo {
  --foo: '20px';
  font-size: var(--foo);
}

/* 有效 */
.foo {
  --foo: 20px;
  font-size: var(--foo);
}

四、作用域

同一个 CSS 变量,可以在多个选择器内声明。读取的时候,优先级最高的声明生效。这与 CSS 的"层叠"(cascade)规则是一致的。

下面是一个例子

<style>
  :root { --color: blue; }
  div { --color: green; }
  #alert { --color: red; }
  * { color: var(--color); }
</style>

<p>蓝色</p>
<div>绿色</div>
<div id="alert">红色</div>

上面代码中,三个选择器都声明了--color变量。不同元素读取这个变量的时候,会采用优先级最高的规则,因此三段文字的颜色是不一样的。

这就是说,变量的作用域就是它所在的选择器的有效范围。

body {
  --foo: #7F583F;
}

.content {
  --bar: #F7EFD2;
}

上面代码中,变量--foo的作用域是body选择器的生效范围,--bar的作用域是.content选择器的生效范围。

由于这个原因,全局的变量通常放在根元素:root里面,确保任何选择器都可以读取它们。

:root {
  --main-color: #06c;
}

五、响应式布局

CSS 是动态的,页面的任何变化,都会导致采用的规则变化。

利用这个特点,可以在响应式布局的media命令里面声明变量,使得不同的屏幕宽度有不同的变量值。

body {
  --primary: #7F583F;
  --secondary: #F7EFD2;
}

a {
  color: var(--primary);
  text-decoration-color: var(--secondary);
}

@media screen and (min-width: 768px) {
  body {
    --primary:  #F7EFD2;
    --secondary: #7F583F;
  }
}

六、兼容性处理

对于不支持 CSS 变量的浏览器,可以采用下面的写法。

a {
  color: #7F583F;
  color: var(--primary);
}

也可以使用@support命令进行检测。

@supports ( (--a: 0)) {
  /* supported */
}

@supports ( not (--a: 0)) {
  /* not supported */
}

七、JavaScript 操作

JavaScript 也可以检测浏览器是否支持 CSS 变量。

const isSupported =
  window.CSS &&
  window.CSS.supports &&
  window.CSS.supports('--a', 0);

if (isSupported) {
  /* supported */
} else {
  /* not supported */
}

JavaScript 操作 CSS 变量的写法如下。

// 设置变量
document.body.style.setProperty('--primary', '#7F583F');

// 读取变量
document.body.style.getPropertyValue('--primary').trim();
// '#7F583F'

// 删除变量
document.body.style.removeProperty('--primary');

这意味着,JavaScript 可以将任意值存入样式表。下面是一个监听事件的例子,事件信息被存入 CSS 变量。

const docStyle = document.documentElement.style;

document.addEventListener('mousemove', (e) => {
  docStyle.setProperty('--mouse-x', e.clientX);
  docStyle.setProperty('--mouse-y', e.clientY);
});

那些对 CSS 无用的信息,也可以放入 CSS 变量。

--foo: if(x > 5) this.width = 10;

上面代码中,--foo的值在 CSS 里面是无效语句,但是可以被 JavaScript 读取。这意味着,可以把样式设置写在 CSS 变量中,让 JavaScript 读取。

所以,CSS 变量提供了 JavaScript 与 CSS 通信的一种途径。

八、参考链接

2022-07-15 11:21

[轉載] 跨域资源共享 CORS 详解

轉載自:阮一峰 跨域资源共享 CORS 详解

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。

它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

本文详细介绍CORS的内部机制。

一、简介

CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。

整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。

因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。

二、两种请求

浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。

只要同时满足以下两大条件,就属于简单请求。

(1) 请求方法是以下三种方法之一:
HEAD
GET
POST
(2)HTTP的头信息不超出以下几种字段:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:只限于三个值
= application/x-www-form-urlencoded
= multipart/form-data
= text/plain

这是为了兼容表单(form),因为历史上表单一直可以发出跨域请求。AJAX 的跨域设计就是,只要表单可以发,AJAX 就可以直接发。

凡是不同时满足上面两个条件,就属于非简单请求。

浏览器对这两种请求的处理,是不一样的。

三、简单请求


3.1 基本流程

对于简单请求,浏览器直接发出CORS请求。具体来说,就是在头信息之中,增加一个Origin字段。

下面是一个例子,浏览器发现这次跨源AJAX请求是简单请求,就自动在头信息之中,添加一个Origin字段。

GET /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

上面的头信息中,Origin字段用来说明,本次请求来自哪个源(协议 + 域名 + 端口)。服务器根据这个值,决定是否同意这次请求。

如果Origin指定的源,不在许可范围内,服务器会返回一个正常的HTTP回应。浏览器发现,这个回应的头信息没有包含Access-Control-Allow-Origin字段(详见下文),就知道出错了,从而抛出一个错误,被XMLHttpRequestonerror回调函数捕获。注意,这种错误无法通过状态码识别,因为HTTP回应的状态码有可能是200。

如果Origin指定的域名在许可范围内,服务器返回的响应,会多出几个头信息字段。

Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8

上面的头信息之中,有三个与CORS请求相关的字段,都以Access-Control-开头。

(1)Access-Control-Allow-Origin
该字段是必须的。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求。
(2)Access-Control-Allow-Credentials
该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。
(3)Access-Control-Expose-Headers
该字段可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。上面的例子指定,getResponseHeader('FooBar')可以返回FooBar字段的值。

3.2 withCredentials 属性

上面说到,CORS请求默认不发送Cookie和HTTP认证信息。如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow-Credentials字段。

Access-Control-Allow-Credentials: true

另一方面,开发者必须在AJAX请求中打开withCredentials属性。

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

否则,即使服务器同意发送Cookie,浏览器也不会发送。或者,服务器要求设置Cookie,浏览器也不会处理。

但是,如果省略withCredentials设置,有的浏览器还是会一起发送Cookie。这时,可以显式关闭withCredentials

xhr.withCredentials = false;

需要注意的是,如果要发送Cookie,Access-Control-Allow-Origin就不能设为星号,必须指定明确的、与请求网页一致的域名。同时,Cookie依然遵循同源政策,只有用服务器域名设置的Cookie才会上传,其他域名的Cookie并不会上传,且(跨源)原网页代码中的document.cookie也无法读取服务器域名下的Cookie。

四、非简单请求


4.1 预检请求

非简单请求是那种对服务器有特殊要求的请求,比如请求方法是PUTDELETE,或者Content-Type字段的类型是application/json

非简单请求的CORS请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight)。

浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest请求,否则就报错。

下面是一段浏览器的JavaScript脚本。

var url = 'http://api.alice.com/cors';
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('X-Custom-Header', 'value');
xhr.send();

上面代码中,HTTP请求的方法是PUT,并且发送一个自定义头信息X-Custom-Header

浏览器发现,这是一个非简单请求,就自动发出一个"预检"请求,要求服务器确认可以这样请求。下面是这个"预检"请求的HTTP头信息。

OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

"预检"请求用的请求方法是OPTIONS,表示这个请求是用来询问的。头信息里面,关键字段是Origin,表示请求来自哪个源。

除了Origin字段,"预检"请求的头信息包括两个特殊字段。

(1)Access-Control-Request-Method
该字段是必须的,用来列出浏览器的CORS请求会用到哪些HTTP方法,上例是PUT
(2)Access-Control-Request-Headers
该字段是一个逗号分隔的字符串,指定浏览器CORS请求会额外发送的头信息字段,上例是X-Custom-Header

4.2 预检请求的回应

服务器收到"预检"请求以后,检查了OriginAccess-Control-Request-MethodAccess-Control-Request-Headers字段以后,确认允许跨源请求,就可以做出回应。

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

上面的HTTP回应中,关键的是Access-Control-Allow-Origin字段,表示http://api.bob.com可以请求数据。该字段也可以设为星号,表示同意任意跨源请求。

Access-Control-Allow-Origin: *

如果服务器否定了"预检"请求,会返回一个正常的HTTP回应,但是没有任何CORS相关的头信息字段。这时,浏览器就会认定,服务器不同意预检请求,因此触发一个错误,被XMLHttpRequest对象的onerror回调函数捕获。控制台会打印出如下的报错信息。

XMLHttpRequest cannot load http://api.alice.com.
Origin http://api.bob.com is not allowed by Access-Control-Allow-Origin.

服务器回应的其他CORS相关字段如下。

Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1728000
(1)Access-Control-Allow-Methods
该字段必需,它的值是逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法。注意,返回的是所有支持的方法,而不单是浏览器请求的那个方法。这是为了避免多次"预检"请求。
(2)Access-Control-Allow-Headers
如果浏览器请求包括Access-Control-Request-Headers字段,则Access-Control-Allow-Headers字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段,不限于浏览器在"预检"中请求的字段。
(3)Access-Control-Allow-Credentials
该字段与简单请求时的含义相同。
(4)Access-Control-Max-Age
该字段可选,用来指定本次预检请求的有效期,单位为秒。上面结果中,有效期是20天(1728000秒),即允许缓存该条回应1728000秒(即20天),在此期间,不用发出另一条预检请求。

4.3 浏览器的正常请求和回应

一旦服务器通过了"预检"请求,以后每次浏览器正常的CORS请求,就都跟简单请求一样,会有一个Origin头信息字段。服务器的回应,也都会有一个Access-Control-Allow-Origin头信息字段。

下面是"预检"请求之后,浏览器的正常CORS请求。

PUT /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
X-Custom-Header: value
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

上面头信息的Origin字段是浏览器自动添加的。

下面是服务器正常的回应。

Access-Control-Allow-Origin: http://api.bob.com
Content-Type: text/html; charset=utf-8

上面头信息中,Access-Control-Allow-Origin字段是每次回应都必定包含的。

五、与JSONP的比较

CORS与JSONP的使用目的相同,但是比JSONP更强大。

JSONP只支持GET请求,CORS支持所有类型的HTTP请求。JSONP的优势在于支持老式浏览器,以及可以向不支持CORS的网站请求数据。

2018-05-12 23:56

JavaScript 正規表示式 跳脫

RegExp.escape = function(str) {
    return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
};

/* use sample */
new RegExp(RegExp.escape("[te()st]"));
2017-03-20 10:13

JavaScript 浮點數計算

一直一來都很少處理 JS 精準運算的問題,大部分的時候 UI 有點不準也不會造成太大的問題,這次用 JS 做一些加減的數字計算,遇到小數的時候就出現運算誤差,既然是 JS 計算機不精準是不行的,User 不可能接受的,找了一堆文章後沒一個靠譜的,但重點都是轉換到整數進行運算,再做浮點位移,整個計算最好盡量避免小數的處理,另外的問題就是位數不能太多。


function transformInt(num1, num2, padZeno, compute) {
    num1 = '' + num1;
    num2 = '' + num2;

    var p1 = 0, p2 = 0;
    try { p1 = num1.split(".")[1].length } catch (e) { }
    try { p2 = num2.split(".")[1].length } catch (e) { }

    if(padZeno){
        while (p1 < p2) { p1++; num1 += '0'; }
        while (p2 < p1) { p2++; num2 += '0'; }
    }

    var int1 = parseInt(num1.replace(".", ""), 10);
    var int2 = parseInt(num2.replace(".", ""), 10);
    return compute(int1, int2, p1, p2);
}


/*浮點數相加*/
function floatAdd(num1, num2) {
    return transformInt(num1, num2, true, function(int1, int2, p1, p2){
        return (int1 + int2) / Math.pow(10, p1);
    });
}

/*浮點數相減*/
function floatSub(num1, num2) {
    return transformInt(num1, num2, true, function(int1, int2, p1, p2){
        return (int1 - int2) / Math.pow(10, p1);
    });
}

/*浮點數相乘*/
function floatMul(num1, num2) {
    return transformInt(num1, num2, false, function(int1, int2, p1, p2){
        return (int1 * int2) / Math.pow(10, p1 + p2);
    });
}

/*浮點數相除*/
function floatDiv(num1, num2) {
    return transformInt(num1, num2, false, function(int1, int2, p1, p2){
        return (int1 / int2) / Math.pow(10, p1 - p2);
    });
}



function unitTest(method, list){
    console.log('=[ ' + method.name + ' ]==============================================');

    for (var i = 0; i < list.length; i++){
        var row = list[i];
        var result = method(row.num1, row.num2);

        if(result == row.ans){
            console.log(row, result);
        }else{
            console.error(row, result);
        }
    };
}

unitTest(floatAdd, [
    {num1:0.11, num2:0.2, ans: 0.31},
    {num1:0.21, num2:0.2, ans: 0.41},
    {num1:0.31, num2:0.2, ans: 0.51},
    {num1:0.41, num2:0.2, ans: 0.61},
    {num1:0.51, num2:0.2, ans: 0.71},
    {num1:0.61, num2:0.2, ans: 0.81},
    {num1:0.71, num2:0.2, ans: 0.91},
    {num1:0.81, num2:0.2, ans: 1.01},
    {num1:0.91, num2:0.2, ans: 1.11},
    {num1:1.01, num2:0.2, ans: 1.21},
]);

unitTest(floatSub, [
    {num1:1.02, num2:0.2, ans: 0.82},
    {num1:1.12, num2:0.2, ans: 0.92},
    {num1:1.22, num2:0.2, ans: 1.02},
    {num1:1.32, num2:0.2, ans: 1.12},
    {num1:1.42, num2:0.2, ans: 1.22},
    {num1:1.52, num2:0.2, ans: 1.32},
    {num1:1.62, num2:0.2, ans: 1.42},
    {num1:1.72, num2:0.2, ans: 1.52},
    {num1:1.82, num2:0.2, ans: 1.62},
    {num1:1.92, num2:0.2, ans: 1.72},
]);

unitTest(floatMul, [
    {num1:10, num2:0.14, ans: 1.4},
    {num1:10, num2:0.24, ans: 2.4},
    {num1:10, num2:0.34, ans: 3.4},
    {num1:10, num2:0.44, ans: 4.4},
    {num1:10, num2:0.54, ans: 5.4},
    {num1:10, num2:0.64, ans: 6.4},
    {num1:10, num2:0.74, ans: 7.4},
    {num1:10, num2:0.84, ans: 8.4},
    {num1:10, num2:0.94, ans: 9.4},
    {num1:10, num2:1.04, ans: 10.4},
]);

unitTest(floatDiv, [
    {num1:1.1, num2:0.1, ans: 11},
    {num1:1.1, num2:0.2, ans: 5.5},
    {num1:0.99, num2:0.3, ans: 3.3},
    {num1:1.1, num2:0.4, ans: 2.75},
    {num1:1.1, num2:0.5, ans: 2.2},
    {num1:1.32, num2:0.6, ans: 2.2},
    {num1:1.54, num2:0.7, ans: 2.2},
    {num1:1.76, num2:0.8, ans: 2.2},
    {num1:2.97, num2:0.9, ans: 3.3},
    {num1:1.1, num2:0.1, ans: 11},
]);

2015-11-26 14:57

天文鐘

2014-11-10 11:45

[轉載] Javascript Char Codes (Key Codes)

轉載自:Javascript Char Codes (Key Codes)

KeyCode
backspace8
tab9
enter13
shift16
ctrl17
alt18
pause/break19
caps lock20
escape27
page up33
page down34
end35
home36
left arrow37
up arrow38
right arrow39
down arrow40
insert45
delete46
048
149
250
351
452
553
654
755
856
957
a65
b66
c67
d68
KeyCode
e69
f70
g71
h72
i73
j74
k75
l76
m77
n78
o79
p80
q81
r82
s83
t84
u85
v86
w87
x88
y89
z90
left window key91
right window key92
select key93
numpad 096
numpad 197
numpad 298
numpad 399
numpad 4100
numpad 5101
numpad 6102
numpad 7103
KeyCode
numpad 8104
numpad 9105
multiply106
add107
subtract109
decimal point110
divide111
f1112
f2113
f3114
f4115
f5116
f6117
f7118
f8119
f9120
f10121
f11122
f12123
num lock144
scroll lock145
semi-colon186
equal sign187
comma188
dash189
period190
forward slash191
grave accent192
open bracket219
back slash220
close braket221
single quote222
  
2014-10-02 09:48

[轉載] Superpower your JavaScript with 10 quick tips - For Beginners

轉載自:Superpower your JavaScript with 10 quick tips - For Beginners

Who doesn't love to write better code? In this article I will list 10 simple and quick JavaScript tips that will help beginners improve their code quality. You might know some of these already. In case you didn't feel free to buy me a beer later.


#1 - Use && and || Operators Like a Boss


Well, JavaScript gives you two awesome logical operators : && and ||. In other languages like Java or C++ they always return a boolean value. But things get a bit interesting when it comes to JavaScript. The && and || operators return the last evaluated operand. Have a look at the following

function getMeBeers(count){
    if(count){
        return count;
    } 
    else{
        return 1;
    }
}

Well, our function is simple and returns the required number of beers. If you specify no argument, it simply gives you a single beer. Here, you can use || to refactor the code as following:

function getMeBeers(count){
    return count || 1;
}

In case of || if the first operand is falsy, JavaScript will evaluate the next operand. So, if no count is specified while calling the function, 1 will be returned. On the other hand, if count is specified then it will be returned (as the first operand is truthy in this case).

Note: null, false,0 (the number), undefined, NaN, and '' (empty string) are falsy values. Any other value is considered truthy.

Now if you want to allow adults only, you can use && as following:

function getMeBeers(age, count){
    return (age>=18) && (count || 1);
}

Instead of :

function getMeBeers(age, count){
    if(age>=18){
        return count || 1;
    }
}

In the above case if age < 18, JavaScript won't even bother evaluating the next operand. So, our function will return. But if the age is actually >= 18, the first operand will evaluate to true and then the next operand will be evaluated.

By the way you should be a careful here. If you pass count as 0, the function will return 1 (as 0 is falsy). So, in a real world app you should be careful while handling numeric values.



#2 - Use === and !== Instead of == and !=


The operators == and != do automatic type conversion, if needed. But === and !== will consider both value and type while comparing and won't do any automatic type conversion. So, to reliably compare two values for equality/non-equality always use === and !==.

10 == '10' //true

10 === '10' //false

10 === 10 //true



#3 - Use Strict mode while writing JS


Strict mode was introduced in ECMA 5. It allows you to put a function or an entire script into strict operating context. The benefits are:

  1. It eliminates some of the silent JavaScript errors by throwing the errors explicitly.
  2. It throws exceptions when relatively unsafe actions take place.
  3. Sometimes strict mode code can run faster than non strict mode code.

<script type="text/javascript">
      'use strict'
      //Strict mode code goes here
</script>

Or,

function strictCode(){
    'use strict'
    //This is a strict mode function
}

As currently all the major browsers support this feature you should start using strict mode.



#4 - Use splice() to remove an array element


If you want to remove an element from an array use splice() instead of delete. delete sets the particular array item to undefined while splice() actually removes the item.

var array=[1,2,3];
delete array[1]; // now array= [1,undefined,3]

array.splice(1,1); //now array=[1,3]



#5 - Use [] to create new array


Use [] to create a new array. Writing var a=[1,2,3] will create a 3-element array whereas new Array(N) will create a physically empty array of N logical length.

Similarly, use var a={} to create an object rather than new Object(). The former one is compact, readable and takes less space. You can also instantly populate the object like:

var a = {
    name: 'John Doe',
    email: 'john@doe.com'
}



#6 - Use String.link() to create Hyperlinks


Many times in JavaScript you will need to generate HTML anchors on the fly. For that you will need some concatenation which may look ugly and messy.

var text="Cool JS Tips";
var url="http://www.htmlxprs.com";
var block='<a href="'+url+'">'+ text +'</a>';

Instead, how about this:

var block=text.link(url); // <a href="http://www.htmlxprs.com">Cool JS Tips</a>



#7 - Cache the length while looping


While looping through a JavaScript array you can cache the length so that the overall performance is better:

for (var i=0,length=array.length; i<length; i++){
    //awesome code goes here
}

Be careful while creating an inner loop. You need to name the length variable differently in the inner one.



#8 - Put 'var' before your variable name


While creating variables don't forget to use the var keyword. If you forget then the variable gets added to the global scope which is definitely a bad thing.

var localVar=12; //this is a local variable

globalVar=12; //variable goes to 'window' global



#9 - Use Closures and Self Executing Functions


Closures, if used carefully and precisely, can take your JS code to a whole new level. There are plenty of tutorials available which can teach you about closures. I will just give an example of closures and self executing functions for creating modular code:

var car=(function(){
    var _name='Benz Velo'; 
    return {
        getName: function(){
            return _name;
        }
    }
})(); //function created and invoked

console.log(car.getName()); //Logs Benz Velo

As you see we just created a function and immediately invoked it. These are called self executing functions or Immediately Invoked Function Expression (IIFE). The function returns an object which is stored in variable car. We also used closure because the object being returned can access the variable _name defined by the parent function. This is helpful for creating modules and emulating private variables.



#10 - There is always room for Optimization


Use jsHint or jsLint to check your code quality and improve further. Also don't forget to minify and concatenate your JS files while deploying your app. Finally, use SourceMaps to make debugging a breeze.



Conclusion


Tips can be unlimited. But I hope these 10 quick tips will help you write better code and superpower your JS-Foo. If you loved this you will love our newsletter as well. Don't forget to subscribe.
2014-05-08 02:58

[AngularJS] 製作 jQuery UI Sortable directive

Html
<div jq-sortable="selectedList">
    <div ng-repeat="item in selectedList">
        <img ng-src="{{item.src}}" />
    </div>
</div>


JavaScript
app.directive('jqSortable', ['$parse', function($parse) {
    return function(scope, element, attrs) {
        /*解析並取得表達式*/
        var expr = $parse(attrs['jqSortable']);
        var $oldChildren;

        element.sortable({
            opacity: 0.7,
            scroll: false,
            tolerance: "pointer",
            start: function() {
                /*紀錄移動前的 children 順序*/
                $oldChildren = element.children('[ng-repeat]');
            },
            update: function(){
                var newList = [];
                var oldList = expr(scope);
                var $children = element.children('[ng-repeat]');

                /*產生新順序的陣列*/
                $oldChildren.each(function(i){
                    var index = $children.index(this);
                    if(index == -1){ return; }

                    newList[index] = oldList[i];
                });

                /*將新順序的陣列寫回 scope 變數*/
                expr.assign(scope, newList);

                /*通知 scope 有異動發生*/
                scope.$digest();
            }
        });

        /*在 destroy 時解除 Sortable*/
        scope.$on('$destroy', function(){
            element.sortable('destroy');
        });
    };
}]);
2014-05-08 02:56

[AngularJS] 製作 Mouse Drag Event directive

Html
<div ng-style="{'top': itemTop, 'left': itemLeft}"
    my-mousedrag="itemTop = itemTop - $deltaY; itemLeft = itemLeft - $deltaX"
></div>

JavaScript
app.directive('myMousedrag', function() {
    return function(scope, element, attrs) {
        var prevEvent;
        element.mousedown(function(event){
            prevEvent = event;

        }).mouseup(function(event){
            prevEvent = null;

        }).mousemove(function(event){
            if(!prevEvent){ return; }

            /*將 element 拖移事件傳遞到 scope 上*/
            scope.$eval(attrs['myMousedrag'], {
                $event: event,
                $deltaX: event.clientX - prevEvent.clientX,
                $deltaY: event.clientY - prevEvent.clientY
            });

            /*通知 scope 有異動發生*/
            scope.$digest();

            prevEvent = event;
        });

        /*在 destroy 時清除事件註冊*/
        scope.$on('$destroy', function(){
            element.off('mousedown mouseup mousemove');
        });
    };
});
2014-05-08 02:54

[AngularJS] 製作 jQuery MouseWheel directive

相依套件:jquery-mousewheel

Html
<div jq-mousewheel="changeSize($event, $delta, $deltaX, $deltaY)"></div>

JavaScript
app.directive('jqMousewheel', function(){
    return function(scope, element, attrs) {

        /*將 element 滾輪事件傳遞到 scope 上*/
        element.on('mousewheel', function (event) {
            scope.$eval(attrs['jqMousewheel'], {
                $event: event,
                $delta: event.delta,
                $deltaX: event.deltaX,
                $deltaY: event.deltaY
            });

            /*通知 scope 有異動發生*/
            scope.$digest();
        });

        /*在 destroy 時清除事件註冊*/
        scope.$on('$destroy', function(){
            element.off('mousewheel');
        });
    };
});
2014-05-08 02:52

[AngularJS] 製作 jQuery scrollTop scrollLeft directive

Html
<div jq-scroll-top="viewerScrollTop" 
      jq-scroll-left="viewerScrollLeft"
></div>

JavaScript
app.directive('jqScrollTop', ['$parse', function($parse){
    return function(scope, element, attrs) {
        /*解析並取得表達式*/
        var expr = $parse(attrs['jqScrollTop']);

        /*監聽變數異動,並更新到 element 上*/
        scope.$watch(attrs['jqScrollTop'], function(value) {
            element.scrollTop(value);
        });

        /*當 element 捲動時更新到變數上*/
        element.on('scroll', function() {
            expr.assign(scope, element.scrollTop());
        });

        /*在 destroy 時清除事件註冊*/
        scope.$on('$destroy', function(){
            element.off('scroll');
        });
    };
}]);

app.directive('jqScrollLeft', ['$parse', function($parse){
    return function(scope, element, attrs) {
        /*解析並取得表達式*/
        var expr = $parse(attrs['jqScrollLeft']);

        /*監聽變數異動,並更新到 element 上*/
        scope.$watch(attrs['jqScrollLeft'], function(value) {
            element.scrollLeft(value);
        });

        /*當 element 捲動時更新到變數上*/
        element.on('scroll', function() {
            expr.assign(scope, element.scrollLeft());
        });

        /*在 destroy 時清除事件註冊*/
        scope.$on('$destroy', function(){
            element.off('scroll');
        });
    };
}]);
2014-03-05 23:38

利用 HTTP Status Codes 傳遞 Ajax 成功失敗的狀態

一般處理 Ajax 回應時會傳送的資訊種類有:資料、成功訊息、錯誤訊息、失敗訊息以及處理狀態,傳遞的資訊種類並不一致,再加上除了資料之外,通常還希望能傳遞處理狀態,這種情況大部分會選擇是以 JSON 的方式傳遞這兩個訊息,以下是常見的幾種格式:

{ code: 1, msg: "OK" }
{ success: true, result: "data", errorMsg: "" }
{ status: 'success', result: [], errorMsg: "" }
//...

但以執行狀態跟操作行為作一個歸納,可以區分以下幾種回傳結果:
資料操作 HTTP Method 成功 錯誤/失敗
檢視(Read) GET 資料 錯誤/失敗訊息
新增(Create)
修改(Update)
刪除(Delete)
POST 成功訊息 錯誤/失敗訊息

從上面的歸納可以看出規律性,接著只要有方法可以傳送處理的狀態,以及能夠區分資料的種類,其實就單純很多,而 HTTP Status Codes 就是用來傳遞 HTTP 的處理狀態,如果利用這個方式來傳遞自訂的處理狀態,這樣 HTTP Content 就可以很單純傳遞資料,讓資料格式不受限於 JSON,還可以使用其他格式(text, xml, html),而且 XMLHttpRequest 本身就有處理 HTTP Status Codes 的能力,而 jQuery.ajax 也有提供 error status 的處理,所以可以利用這個來定義狀態的處理,在 HTTP Status Codes 有幾個已經定義狀態,很適合用來回傳處理狀態的資訊:

400 Bad Request 錯誤的請求 適用在表單內容的錯誤,如必填欄位未填、Email 格式錯誤
403 Forbidden 沒有權限,被禁止的 適用在沒有登入或權限不足
500 Internal Server Error 內部服務器錯誤 適用在程式的錯誤


jQuery 接收資訊的範例
$.ajax({
    type: "POST",
    url: document.location,
    success: function (data, textStatus, jqXHR) {
        alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(jqXHR.responseText);
    }
});


PHP 傳遞錯誤訊息的範例
if (php_sapi_name() == 'cgi'){
    header("Status: 400 Bad Request");
}else{
    header("HTTP/1.0 400 Bad Request");
}
exit("儲存失敗!!");


C# MVC 傳遞錯誤訊息的範例
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 400;
return Content("儲存失敗!!");
2014-02-18 22:46

[jQuery] $.log 與 $.fn.dump

記錄一下,偷懶的 console.log
if ($ && $.fn) {
    $.log = (window['console'] && typeof(console.log)=='function') ?
        function () { console.log.apply(console, arguments); } :
        $.noop;

    $.fn.dump = function (tag) {
        var args = Array.prototype.slice.call(arguments);
        args.push(this);

        $.log.apply($, args);
        return this;
    }
}


// use
$.log('ok');

$('img').dump();

$('div').dump('my tag');
2014-02-18 22:26

[jQuery] 製作 $.fn.delayAll

jQuery 有提供 delay 這個方法,可惜只能用在動畫操作上,想要做到下面的事情就只能用 setTimeout 了。
// not working
$('div').css('color','red').delay(200).css('color','blue');


// use setTimeout
$('div').css('color','red');

setTimeout(function(){
    $('div').css('color','blue');
}, 200);


稍微研究了一下,發現 jQuery 本身有製作 queue 的功能,這個用來存放 delay 後要執行動作的紀錄器,最後只要對 jQuery Object 作一個代理器的包裝,就可以達到想要的目的了。
var queueName = 'delayAll';

/*定義 jQuery Delay 代理類別*/
function jQueryDelay(jqObject, duration){
    /*將缺少的成員屬性補上*/
    for(var member in jqObject){
        if(!$.isFunction(jqObject[member]) || !this[member]){
            this[member] = jqObject[member];
        }
    }

    /*新增 delay 時間並啟動 queue*/
    jqObject
        .delay(duration, queueName)
        .dequeue(queueName);

    /*紀錄 jQuery 物件*/
    this._jqObject = jqObject;
};


/*為所有的 jQuery 方法製作 proxy*/
for(var member in $.fn){
    if(!$.isFunction($.fn[member])){ continue; }

    jQueryDelay.prototype[member] = function(){
        var jqObject = this._jqObject;
        var args = Array.prototype.slice.call(arguments);
        var mothed = arguments.callee.methodName;

        /*將需要執行動作加入 queue*/
        jqObject.queue(queueName, function(next) {
            jqObject[mothed].apply(jqObject, args);
            next();
        });

        return this;
    };

    /*紀錄方法名稱,在 proxy 時會需要參考到*/
    jQueryDelay.prototype[member].methodName = member;
}


/*允許多次串接的可能*/
jQueryDelay.prototype.delayAll = function(duration){
    this._jqObject.delay(duration, queueName);
    return this;
};


/*用 jQueryDelay 將原本的 jQuery Object 包裝起來*/
$.fn.delayAll = function(duration){
    return new jQueryDelay(this ,duration);
};


使用範例:
$('div').css('color','#f00')
    .delayAll(2000).css('color','#0f0')
    .delayAll(2000).css('color','#00f');


檔案下載:jquery.delayAll.js