views:

63

answers:

1

I want to modify the code in this AJAX example to get results from Google.

I take it out the line with the Random() method call, but how do I work with the query string in the JavaScript? How can I best do this using XMLHttpRequest to manually build the request (this is for testing so has to be manually done, as opposed to using a framework).

Thanks

+2  A: 

You cannot use XMLHttpRequest with an absolute URL like http://www.google.com/....

The browser will prevent cross-site scripting. You have to use a relative path, otherwise most browsers will simply return an empty responseText.

As one possible workaround, you could set up a very simple reverse proxy (using mod_proxy if you are on 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     /ajax/     http://www.google.com/search

In this case, the browser would be requesting /ajax/?hl=en&source=hp&q=test but in fact the server would serve this by acting as a proxy to http://www.google.com/search?hl=en&source=hp&q=test.

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

Daniel Vassallo
So a relative url which is on the same server only? Can I use local files on my desktop (Eg to read from)?
dotnetdev
Basically Yes. The files have to be accessed with a relative URL, like that in the w3schools example you provided. However check out my updated answer for a possible workaround by using a reverse proxy.
Daniel Vassallo
Good answer. Just one thing: So if I run a page on my browser locally, I can still work with a file which may be in the same folder? While local only. I tried this today but got 0 (basically nothing read in a populated .txt file).
dotnetdev
Yes you can, as long as you do not use a file path like: `"file:///C:/path_to/file.txt"`. Simply use `"file.txt"` in `XMLHttpRequest.open()`.
Daniel Vassallo
Ah, tried it while I was not on this thread, is working now. Must be some oversight on my work machine.
dotnetdev
Great news!... :)
Daniel Vassallo