Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a url from javascript

Tags:

javascript

Is there a way to call a url and get a response using javascript? I need the equivalent of ASP.NET:

WebRequest req = HttpWebRequest.Create("http://someurl.com");
WebResponse webResponse = req.GetResponse();

I have an external url that holds some information I need and I want to call this url from javascript and parse the response in order to determine what to do in my application.

like image 780
lnetanel Avatar asked May 25 '09 14:05

lnetanel


People also ask

How do I get the URL of a website using JavaScript?

You can simply call the window. location. href property which will return you the complete URL of the webpage including hostname, pathname, and query string.

How do you call a URL in HTML?

Adding an HTML Phone Number Call Link to your Website Href=tel: creates the call link. This tells the browser how to use the number. “Tel: 123-456-7890 “creates the HTML phone number. The number within the quotes is the number it will call.

Can you embed JavaScript in URL?

Yes, it can contain executable code (of any kind, including javascript) since URL is a plain string data.

How do I run a script in URL?

Something like: http://www.mysite.com/mypage.php?alert(HelloWorld); That when this url is visited then it should run the script.


1 Answers

You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the get method.

$.get('http://someurl.com',function(data,status) {
      ...parse the data...
},'html');

If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.

Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.

like image 189
tvanfosson Avatar answered Oct 06 '22 06:10

tvanfosson