jquery-mockjax是用于mock 前台ajax向后台请求的返回数据。
原理很简单
在你js代码要发送ajax请求的地方断点一下,然后比较在【引入jquery-mockjax】 和 【没有引入jquery-mockjax】的情况下$.ajax.toString()的值情况。
很明显,引入jquery-mockjax时,这个mock库会对jquery提供的ajax函数做替换。这样就很容易能mock起来。
$.mockjax({ url: ‘/restful/fortune‘, responseTime: 750, responseText: { status: ‘success‘, fortune: ‘Are you a turtle?‘ } });
url上可以做很多文章,支持:
url:
‘*‘
url:
‘/data/*‘
url: /^/data/(quote|tweet)$/i
只要给其responseText responseXML设置相应的值即可
xml的例子:
$.mockjax({ url: ‘/restful/api‘, // Need to include the xmlDOM plugin to have this translated into a DOM responseXML: ‘<document><quote>Hello world!</quote></document>‘ });
$.mockjax({ url: ‘/restful/api‘, proxy: ‘/mocks/data.json‘ });
$.mockjax({ url: ‘/restful/api‘, response: function() { this.responseText = ‘Hello world!‘; } });
$.mockjax({ url: ‘/restful/api‘, // Simulate a network latency of 750ms responseTime: 750, responseText: ‘A text response from the server‘ });
$.mockjax({ url: ‘/restful/api‘, // Server 500 error occurred status: 500, responseTime: 750, responseText: ‘A text response from the server‘ });
$.mockjax({ url: ‘/restful/api‘, contentType: ‘text/json‘, responseText: { hello: ‘World!‘ } });
$.mockjax({ url: ‘/restful/api‘, contentType: ‘text/json‘, responseText: { hello: ‘World!‘ }, headers: { etag: ‘xyz123‘ } });
ref: http://appendto.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development/
原文:http://www.cnblogs.com/simoncook/p/4864353.html