首页 > Web开发 > 详细

jquery-mockjax初试

时间:2015-10-09 16:53:51      阅读:376      评论:0      收藏:0      [点我收藏+]

1. 原理

jquery-mockjax是用于mock 前台ajax向后台请求的返回数据。

原理很简单

在你js代码要发送ajax请求的地方断点一下,然后比较在【引入jquery-mockjax】 和 【没有引入jquery-mockjax】的情况下$.ajax.toString()的值情况。

很明显,引入jquery-mockjax时,这个mock库会对jquery提供的ajax函数做替换。这样就很容易能mock起来。

2. 提供的基本特性

1. 根据指定的url模拟基本本的json数据

$.mockjax({
  url: ‘/restful/fortune‘,
  responseTime: 750,
  responseText: {
    status: ‘success‘,
    fortune: ‘Are you a turtle?‘
  }
});

url上可以做很多文章,支持:

url: ‘*‘

url: ‘/data/*‘

url: /^/data/(quote|tweet)$/i

2. 可以是返回text,xml

只要给其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>‘
});

3. 可以用proxy指向一个json文件,将json文件中的内容当做json数据mock回去

$.mockjax({
  url: ‘/restful/api‘,
  proxy: ‘/mocks/data.json‘
});

4.response属性可以指向function 以达到mock数据可编程的目的(动态指定)

$.mockjax({
  url: ‘/restful/api‘,
  response: function() {
    this.responseText = ‘Hello world!‘;
  }
});

5.通过responseTime设置的值mock超时时间

$.mockjax({
  url: ‘/restful/api‘,
  // Simulate a network latency of 750ms
  responseTime: 750,
  responseText: ‘A text response from the server‘
});

6.通过status 设置的值mock http状态

$.mockjax({
  url: ‘/restful/api‘,
  // Server 500 error occurred
  status: 500,
  responseTime: 750,
  responseText: ‘A text response from the server‘
});

7. 通过contentType设置的值mock contentType类型

$.mockjax({
  url: ‘/restful/api‘,
  contentType: ‘text/json‘,
  responseText: {
    hello: ‘World!‘
  }
});

8.给headers设置一个json对象,mock header信息

$.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/

jquery-mockjax初试

原文:http://www.cnblogs.com/simoncook/p/4864353.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!