开发者

Download file and display contents with javascript

I have a simple webpage which has a link, o开发者_C百科n pressing it a file is downloaded(rest web service call). I need to read the file and display the contents using javascript. How do I do this?


If you have access to the server where the REST web service is hosted, you can use JSONP.

Otherwise, you will have to work around the same-origin policy restrictions.

As one possible workaround, you could set up a very simple reverse proxy (with mod_proxy if you are using Apache). This would allow you to use relative paths in your AJAX request, while the HTTP server would be acting as a proxy to any "remote" location.

The fundamental configuration directive to set up a reverse proxy in mod_proxy is the ProxyPass. You would typically use it as follows:

ProxyPass     /web-services/     http://third-party.com/web-services/

In this case, the browser would be requesting /web-services/service.json but the server would serve this by acting as a proxy to http://third-party.com/web-services/service.json.

If you are using IIS, you may want to use the Managed Fusion URL Rewriter and Reverse Proxy to set up the reverse proxy.


EDIT:

Further to the comment below, since the web service is on the same domain, there is no need to worry about the same origin policy. Simply use XMLHttpRequest. You can start by checking out the article at ajaxpatterns.org:

  • XMLHttpRequest Call


Using jquery

$.getJSON(myResourceFileURL,
 function parseResults(json){
    //json is the contents of the file
 }
);


As you're using JQuery:

http://api.jquery.com/jQuery.getJSON/

Your text file will be passed to the "success" function that you set up. Your success function can write the contents to the page, using a document.write or similar.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜