'); //创建form元素
if (data) {//通常为false
for (var i in data) {
jQuery('').appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。
}
}
var oldElement = jQuery('#' + fileElementId); //得到页面中的对象
var newElement = jQuery(oldElement).clone(); //克隆页面中的对象
jQuery(oldElement).attr('id', fileId); //修改原对象的id
jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
//set attributes
jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body'); //把动态form插入到body中
return form;
},
ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
var frameId = 'jUploadFrame' + id; //动态iframe的id
var formId = 'jUploadForm' + id; //动态form的id
// Watch for a new set of requests
if (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生
jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
}
var requestDone = false; //请求完成标志
// Create the request object
var xml = {};
if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
// Wait for a response to come back
var uploadCallback = function (isTimeout) {//回调函数
var io = document.getElementById(frameId); //得到iframe对象
try {
if (io.contentWindow) {//动态iframe所在窗口对象是否存在
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {//动态iframe的文档对象是否存在
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应
requestDone = true; //请求完成
var status;
try {
status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表示请求成功
// Make sure that the request was successful or notmodified
if (status != "error") {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
// If a local callback was specified, fire it and pass it the data
if (s.success)
s.success(data, status); //执行上传成功的操作
// Fire the global callback
if (s.global)
jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else
jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if (s.global)
jQuery.event.trigger("ajaxComplete", [xml, s]);
// Handle the global AJAX counter
if (s.global && ! --jQuery.active)
jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete)
s.complete(xml, status);
jQuery(io).unbind();//移除iframe的事件处理程序
setTimeout(function () {//设置超时时间
try {
jQuery(io).remove();//移除动态iframe
jQuery(form).remove();//移除动态form
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if (s.timeout > 0) {//超时检测
setTimeout(function () {
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");//如果请求仍未完成,就发送超时信号
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);//传入的ajax页面导向url
jQuery(form).attr('method', 'POST');//设置提交表单方式
jQuery(form).attr('target', frameId);//返回的目标iframe,就是创建的动态iframe
if (form.encoding) {//选择编码方式
jQuery(form).attr('encoding', 'multipart/form-data');
}
else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();//提交form表单
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数
return { abort: function () { } };
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data);
// evaluate scripts within html
if (type == "html")
jQuery("
function Person(name,age,job){ this.name=name; this.age=age; this.job=job;
}var person=new Person('match',28,'Software Engineer');
console.log(person.name);//match
如果没有使用new操作符,原本针对Person对象的三个属性被添加到window对象
function Person(name,age,job){ this.name=name; this.age=age; this.job=job;
}
var person=Person('match',28,'Software Engineer');
console.log(person);//undefinedconsole.log(window.name);//match
<base href="">
jQuery i18n
$().ready(
function() {
$("#sub").click(
function() {
var name = $("#username").val();
var age = 18;
var user = {"username":name,"age":age};
$.ajax({
url : 'hello.json',
type : 'POST',
data : JSON.stringify(user), // Request body
contentType : 'application/json; charset=utf-8',
dataType : 'json',
success : function(response) {
//请求成功
alert("你好" + response.username + "[" + response.age + "],当前时间是:" + response.time + ",欢迎访问:http://www.zifangsky.cn");
},
error : function(msg) {
alert(msg);
}
});
});
});
(2)一个简单的model类User,代码如下:
package cn.zifangsky.controller;
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
(3)controller类TestController.java:
package cn.zifangsky.controller;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
@Scope("prototype")
public class TestController {
/**
* 转到页面
*/
@RequestMapping(value = "/hello.html")
public ModelAndView list() {
ModelAndView view = new ModelAndView("index");
return view;
}
/**
* ajax异步请求, 请求格式是json
*/
@RequestMapping(value = "/hello.json", method = { RequestMethod.POST })
@ResponseBody
public Map hello(@RequestBody User user) {
// 返回数据的Map集合
Map result = new HashMap();
Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 返回请求的username
result.put("username", user.getUsername());
// 返回年龄
result.put("age", String.valueOf(user.getAge()));
// 返回当前时间
result.put("time", format.format(new Date()));
return result;
}
}
var deferred = $.Deferred();
var promise = deferred.promise();
promise.then(function(v) {
console.log(`then with ${v}`);
}).done(function(v) {
console.log(`done with ${v}`);
});
deferred.resolve("resolveData");
// tests/scripts/badHandlerTest.jsit('returns a value without errors', function() { var fn = function() { return 1;
}; var result = badHandler(fn);
result.should.equal(1);
});
it('returns a null with errors', function() { var fn = function() { throw new Error('random error');
}; var result = badHandler(fn);
should(result).equal(null);
});
如果出现问题,错误处理程序就会返回 null。fn( ) 回调函数可以指向一个合法的方法或错误。
以下的点击事件会继续进行事件处理:
// scripts/badHandlerDom.js(function (handler, bomb) { var badButton = document.getElementById('bad'); if (badButton) {
badButton.addEventListener('click', function () {
handler(bomb);
console.log('Imagine, getting promoted for hiding mistakes');
});
}
}(badHandler, error));
// scripts/uglyHandler.jsfunction uglyHandler(fn) { try { return fn();
} catch (e) { throw new Error('a new error');
}
}
处理异常的方式如下所示:
// tests/scripts/uglyHandlerTest.jsit('returns a new error with errors', function () { var fn = function () { throw new TypeError('type error');
};
should.throws(function () {
uglyHandler(fn);
}, Error);
});
// tests/scripts/uglyHandlerImprovedTest.jsit('returns a specified error with errors', function () { var fn = function () { throw new TypeError('type error');
};
should.throws(function () {
uglyHandlerImproved(fn);
}, SpecifiedError);
});
// scripts/errorAjaxHandlerDom.jswindow.addEventListener('error', function (e) { var stack = e.error.stack; var message = e.error.toString(); if (stack) {
message += 'n' + stack;
} var xhr = new XMLHttpRequest();
xhr.open('POST', '/log', true); // Fire an Ajax request with error details xhr.send(message);
});
// scripts/asyncHandler.jsfunction asyncHandler(fn) { try { // This rips the potential bomb from the current context
setTimeout(function () {
fn();
}, 1);
} catch (e) { }
}
通过单元测试来查看问题:
// tests/scripts/asyncHandlerTest.jsit('does not catch exceptions with errors', function () { // The bomb
var fn = function () { throw new TypeError('type error');
}; // Check that the exception is not caught
should.doesNotThrow(function () {
asyncHandler(fn);
});
});