views:

88

answers:

3

I have a simple webpage which has a link, on 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?

+1  A: 

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:

Daniel Vassallo
I am requesting data from the same domain, so what do i need to do in this case?
Pranav
If your webservice is on the same domain, you can use AJAX using XMLHttpRequest: http://en.wikipedia.org/wiki/XMLHttpRequest. You will be returned the data in the `responseText` property.
Daniel Vassallo
A: 

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.

Ash Eldritch
+2  A: 

Using jquery

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