我正在努力将现有应用程序的UI从GWT移植到Backbone。后端保持不变。后端中的所有请求都由单个端点处理。 URL编码的参数确定响应应该是什么。例如:
http://localhost/adminNPS?request=getDashboard&object=dash&id=2
http://localhost/adminNPS?request=getDashboard&object=dash&id=3
http://localhost/adminNPS?request=saveDashboard&object=dash&id=1 ... {json}
http://localhost/adminNPS?request=getUser&object=user
http://localhost/adminNPS?request=createUser&object=user ... {json}
http://localhost/adminNPS?request=getUserPermissions&object=user
不要问谁设计了这个方案= P ..现在,我必须设计Backbone Models / Collections来连接到这个端点并使用mockjax来模拟ajax调用。所以我现在有两个问题。 / p>
如何在mockjax
中为此创建模拟调用?使用类似下面的东西工作正常..但需要URL中参数的精确顺序.. mockjax
的文档状态参数可以与data: { key: value }
哈希匹配..但这对我不起作用。有人能指导我进一步指导我吗?
$.mockjax({
url: http://localhost/adminNPS?request=getDashboard&object=dash&id=2,
responseText: { ... }
});
如何对模型进行编码,例如,DashboardModel在获取时访问http://localhost/adminNPS?request=getDashboard&object=dash&id=3
,在保存时访问http://localhost/adminNPS?request=saveDashboard&object=dash&id=3
..
答案 0 :(得分:1)
关于使用data
选项匹配查询参数,这是documented bug in Mockjax。基本上,请求匹配器仅适用于$.ajax()
调用上的数据对象,而不是查询字符串。
那就是说,有两种方法可以解决这个问题:
1)您可以使用regex version of the url
matcher:
$.mockjax({
url: /adminNPS?request=[^&]+&object=[^&]+&id=[0-9]+/i, // tweak to your needs
...
});
2)或者您可以通过传递函数来使用fully custom matching ability:
$.mockjax(function(settings) {
// examine `settings.url` which would be something like:
// http://localhost/adminNPS?request=getDashboard&object=dash&id=2
var q = settings.url.split('?')[1].split('&');
var data = {}; // will be a hash of the query data
for (var i=0, l=q.length; i<l; ++i) {
data[q[i].split('=')[0]] = q[i].split('=')[1];
}
// Now you can look at the `data` object to do your matching
if ( /* the URL matches what you want */ ) {
return {
response: function () {
this.responseText = { ... }; /* whatever you want the response to be */
}
};
}
return; // no match
});
已更新,显示您可能如何调查查询字符串...