Mockjax可以处理Json文件中的单个id Api吗?

Can Mockjax handle single IDs Api from Json file

本文关键字:id 单个 Api 处理 Json 文件 Mockjax      更新时间:2023-09-26

我第一次使用Mockjax模拟Restful API,它将返回给定id的一系列数据。现在我有一个json文件,有几个项目,我想有一个函数在Mockjax(或必要时)只返回查询的ID。我怎样才能做到这一点?

当前代码:

$.mockjax({
    url: "/Api/Cases/{caseId}",
    proxy: "/mocks/cases nuevo.json",
    dataType: 'json',
    responseTime: [500, 800]
});
$.ajax({
    type: 'GET',
    url: '/Api/Cases/',
    data: {caseId: taskId},
    success: function(data){
        //use the returned
        console.log(data);
    }
});
当前错误:

GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)

问得好…是的,你能做到。但是您必须使用response回调函数自己编写功能,然后对文件进行"真正的"Ajax请求(而不是使用proxy选项)。下面我只是进行另一个$.ajax()调用,因为我没有为设置端点的模拟处理程序,Mockjax让它通过。

请注意,设置URL参数与您建议的略有不同,下面是模拟设置:

$.mockjax({
    url: /'/Api'/Cases'/('d+)/,  // notice the regex here to allow for any ID
    urlParams: ['caseID'],       // This defines the first matching group as "caseID"
    responseTime: [500, 800],
    response: function(settings, mockDone) {
        // hold onto the mock response object
        var respObj = this;
        // get the mock data file
        $.ajax({
            url: 'mocks/test-data.json',
            success: function(data) {
                respObj.status = 200;
                // We can now use "caseID" off of the mock settings.urlParams object
                respObj.responseText = data[settings.urlParams.caseID];
                mockDone();
            },
            error: function() {
                respObj.status = 500;
                respObj.responseText = 'Error retrieving mock data';
                mockDone();
            }
        });
    }
});
但是,您的代码还有一个问题,您的Ajax调用不将ID添加到URL,而是将其添加到查询字符串。如果希望使用该API端点,还需要更改源代码$.ajax()调用。下面是新的Ajax调用:
$.ajax({
    type: 'GET',
    url: '/Api/Cases/' + taskId, // this will add the ID to the URL
    // data: {caseId: taskId},   // this adds the data to the query string
    success: function(data){
        //use the returned
        console.log(data);
    }
});

注意,这里假定模拟数据类似于:

{
    "13": { "name": "Jordan", "level": 21, "id": 13 },
    "27": { "name": "Random Guy", "level": 20, "id": 27 }
}

我最终做的是:我已经离开了$.mockjax函数不变,我已经操纵了ajax请求内的数据,使用jquery的$.grep函数如下:

$.ajax({
        type: 'GET',
        url: '/Api/Cases/' + taskId,
        success: function(data){
        //note you have to parse the data as it is received as string
            data = JSON.parse(data);
            var result = $.grep(data, function(e){ return e.caseId ==  taskId; });
            //since i'm expecting only one result, i pull out the result on the 0 index position
            requestedData = result[0];
        }
});

$.grep()方法根据需要从数组中删除项目,以便所有剩余的项目通过提供的测试,参见Jquery API,并且由于我们的测试是元素的caseId属性等于发送的taksId变量,它将返回与给定Id匹配的所有元素,在这种情况下,只有一个,这就是为什么我只取0索引位置的结果requestedData = result[0];

* *注意:* *一个更合适的解决方案是我所做的和@jakerella的答案之间的混合,因为他们的方法实现了mockjacx函数内部的find元素方法,而我的函数假定一个通常的JSON响应:

[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]