开发者

URL returns a number. How do I assign that url as a value to a variable?

I'm doing a lending rates page. I have a url which, upon entering in a browser, returns a number.

I need to be able to do (in human terms) this:

var x=http://www.wherever.com/assest?cmsid=P-2870159

in the html:

<td>Our rate today is:<var x></td>

So in javascript, I'm just blanking on how I get the value returned from the url to be assigned to a variable that I can document.write the 开发者_高级运维variable into an html file wherever I need the value.

The url stays the same but the number it somehow generates is dynamic.

I don't have full access to where the url is actually hosted.

NOTE: the url above is fictitious but the ?cmsid on is real so that is the proper format.


You are looking to make an AJAX call.

A simple jQuery example:

$.get('http://www.wherever.com/assest?cmsid=P-2870159', function(data) {
  x = data;
  alert('x is now' + x);
});

Note that AJAX is asynchronous. That means that you can't work with x straight away in your code, but you have to put anything that works with the fetched result into the success callback (the function(data) part in the above example).

It is also possible to make the above example synchronous (so that x is available in the script afterwards) but that is not recommended, as it could freeze the browser when the request times out.

AJAX is a technique independent from jQuery, but as you can see the JavaScript frameworks take a lot of hassle out of what would be a 10-20 line code block using plain JavaScript and the XMLHTTPRequest object.

Note that like @Paul Dixon says, you can't do cross-domain AJAX calls. The only technique to do that is JSONP.


The quick answer, thought it may not be the best is to do something like

<td>Our rate today is<iframe id='rate' src='http://www.wherever.com/assest?cmsid=P-2870159
'></iframe></td>

Then style with css the iframe so that is inline and whatever size you need.

To avoid the same origin problem you can always do an HTTP request to the server and let the server get the number and then return it. Though, I'm thinking it would be better just to the hole thing server side and just insert it into the HTML before the page is sent to the browser.

<td>Our rate is today is <?php getRate(); ?></td>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜