开发者

Right way to build out JSON config for Restful Web Service

I know the question is a little vague, but I'm not sure how to explain it.

I'm building a sencha-touch app that will be communicating with an ASP.NET MVC WebService.

Instead of putting all the restful URL's all over the place within the app, I'm thinking of setting up a config file that will contain the WebService information. Below is what I have so far.

var config = {
    WebService: {
        Url: 'http://webservice.myapp.com/',
        Vimeo: {
            Read: 'Vimeo/Read'
        },
        Contact: {
            Communicate: 'Contact/Communicate',
            Contact:'Contact/Contact'
        }
    }
};

And though this works, when I setup my JSONP Request, it looks a little funny.

$.ajax(config.WebService.Url + config.WebService.Vimeo.Read, {
    crossDomain: true,
    dataType: "jsonp",
    success: function (data) {
        $.each(dat开发者_JAVA百科a, function (i, item) {
            videosToShow = data;
        });
    }
});

Is there a better/right way to approach this?


The jQuery ajax object is a good general wrapper for xmlhttp, but since you're building additional level of abstraction why not wrap $.ajax in your own object which accepts a config type and handles the ajax and any errors that may result gracefully.

You could design it so your calls looked something like:

root.ajax(config.WebService.Vimeo.Read, callback);

You could then configure the url root in your wrapped ajax object once on startup.

root.ajax.rootUrl = config.WebService.Url


I've sort of decided to go a different direction.

I've built a method called WebService(controller, action)

Whereby I submit it as follows

$.ajax(WebService("myController", "myAction"), {
    crossDomain: true,
    dataType: "jsonp",
    success: function (data) {
        $.each(data, function (i, item) {
            // do stuff
        });
    }
});

Works like a champ.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜