By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,175 Members | 1,689 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,175 IT Pros & Developers. It's quick & easy.

JSON - Cross domain request

P: n/a
I am looking to make a small web app that will return the status of a
website from the client browser. I tried this with AJAX and it worked
great locally, but did not work for remote users accessing the page, I
ran into the security problem with making a cross domain request.

I have been reading that with JSON a cross domain request can be
accomplished, but have not been able to find any examples on how to use
it or how to get the return code from retrieving a web page.

I want to make these requests from the client browser, and it will not
work as a proxy request from my web server. Any ideas on how to make
this work? Please provide a working example if available...
Thanks

Apr 13 '06 #1
Share this Question
Share on Google+
13 Replies


P: n/a


tr****@gmail.com wrote:
I want to make these requests from the client browser, and it will not
work as a proxy request from my web server. Any ideas on how to make
this work?


An image object or an img element object can be used with an onload and
onerror handler e.g.
var img = new Image();
img.onerror = function (evt) {
// handle error case
};
img.onload = function (evt) {
// handle load
};
// now try to load a test image on that server you want to check e.g.
img.src = 'http://example.com/test.gif?time=' + new Date().getTime();
That requires that you can put an image on the server you want to check.
And you don't get any status code, you have to live with either onerror
or onload being fired.

A different possible approach is to put or generate a script on that
server e.g.
<script type="text/javascript"
src="http://example.com/status.js"></script>
that at least allows you to load a resource from a server being a
different origin than the server the HTML document comes from, e.g. you
could do
var serverStatus = false;
with inline script and then status.js on the server sets
serverStatus = true;

I don't see how JSON would help to work around the same origin policy,
it is just a data exchange format that does not help you to make
requests to servers you can't access due to security restrictions.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Apr 13 '06 #2

P: n/a
Your examples make sense, but not exactly what I am looking for.
Basically I want a test page that will give the status of a webpage
based on the client experience. So I would want to status sites like
http://www.yahoo.com or http://www.google.com for the return code. If
you visit the page you would get a 200 return code, but if I visit the
page I might get a different return code because of proxy issues, or
some other local network issue. I want to be able to compare the user
experience from different locations.

I found this on the Yahoo site, but I could not find any example on how
to implement:

Use JSON and dynamic <script> tags instead of XML and XMLHttpRequest.
You can get around the browser security problem altogether by making
your web services request directly inside a <script> tag. If the Yahoo!
Web Service you're using can output JSON (using the output=json and
callback=function parameters), the data you get back from the web
service is evaluated as a JavaScript object when the page is loaded.

How could I use the above to accomplish what I am trying to do?? Thanks!

Apr 13 '06 #3

P: n/a


tr****@gmail.com wrote:

Use JSON and dynamic <script> tags instead of XML and XMLHttpRequest.
You can get around the browser security problem altogether by making
your web services request directly inside a <script> tag. If the Yahoo!
Web Service you're using can output JSON (using the output=json and
callback=function parameters), the data you get back from the web
service is evaluated as a JavaScript object when the page is loaded.

How could I use the above to accomplish what I am trying to do??


What they suggest there is the use of a script element to load a script
from that server, what I had already suggested, only that they seem to
intend to dynamically create the script element (e.g.
document.createElement('script')
) and then have the loaded script call a defined callback function in
your page. My example suggestion was a bit simpler, just a global
variable was used for the data exchange, they want you to use a callback
function the script can call and pass in data in the JSON format. That
is of course possible, only it does not help you to get any status from
that server if there is no special script available on the server that
you can load. So what they do is offer web services you or anyone else
can call using a script element while you want to get a status of any
server where there is no script available.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Apr 13 '06 #4

P: n/a
tr****@gmail.com writes:
I have been reading that with JSON a cross domain request can be
accomplished,


That sounds like someone misunderstanding the concept.
JSON is a format for representing data. It does not make any
assumptions about how those data are transferred between computers
(if at all).

What someone might be thinking of is that a <script src="..."> element
can load Javascript from a different source than the containing
document. JSON won't help you there, since loading a JSON expression
as a script element has no measureable effect (unless you can read the
text of the script element after it is loaded, but not all browsers
support that). You can send standard Javascript with side effects,
but then it's not JSON any more.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Apr 14 '06 #5

P: n/a
Lasse Reichstein Nielsen said the following on 4/13/2006 11:04 PM:
tr****@gmail.com writes:
I have been reading that with JSON a cross domain request can be
accomplished,


That sounds like someone misunderstanding the concept.


<URL: http://borkweb.com/story/look-ma-cross-domain-scripting >

I think a lot of that misunderstanding comes, in part, from that
website. It implies that JSON is the secret to it when it isn't. The
secret to it is dynamic script tags.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Apr 14 '06 #6

P: n/a
Randy Webb <Hi************@aol.com> writes:
<URL: http://borkweb.com/story/look-ma-cross-domain-scripting >

I think a lot of that misunderstanding comes, in part, from that
website. It implies that JSON is the secret to it when it isn't. The
secret to it is dynamic script tags.


True. It's the Yahoo web-service format that uses JSON, but what it
sends is not pure JSON, but a function call with an argument that is a
JSON expression. It's good use of JSON, but it's not just that. It could
send any Javascript if it wanted, and it would still work as well.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Apr 14 '06 #7

P: n/a

tr****@gmail.com napisal(a):
I want to make these requests from the client browser, and it will not
work as a proxy request from my web server. Any ideas on how to make
this work? Please provide a working example if available...


First i agree with my followers... another way to get status code is to
write java applet and put it as object with width and height equal to 0
px and visibility to hidden (css). Inside java aplet you can write
method to make call to any server you want, and call that method from
JavaScript using LiveConnect. Example:

ScriptableClock.java
-----------------------------
public void setTimeZone(String zone) {
stop();
timeZone = (zone.startsWith("GMT")) ? true : false;
start();
}
public void setFont(String newFont, String newStyle, String newSize) {
stop();
if (newFont != null && newFont != "")
fontName = newFont;
if (newStyle != null && newStyle != "")
setFontStyle(newStyle);
if (newSize != null && newSize != "")
setFontSize(newSize);
displayFont = new Font(fontName, fontStyle, fontSize);
start();
}
public void setColor(String newbgColor, String newfgColor) {
stop();
bgColor = parseColor(newbgColor);
fgColor = parseColor(newfgColor);
start();
}
public String getInfo() {
String result = "Info about ScriptableClock.class\r\n";
result += "Version/Date: 1.0d1/2 May 1996\r\n";
result += "Author: Danny Goodman (da****@dannyg.com)\r\n";
result += "Public Variables:\r\n";
result += " (None)\r\n\r\n";
result += "Public Methods:\r\n";
result += " setTimeZone(\"GMT\" | \"Locale\")\r\n";
result += " setFont(\"fontName\",\"Plain\" |\"Bold\" |
\"Italic\",
\"fontSize\")\r\n";
result += " setColor(\"bgColorName\",
\"fgColorName\")\r\n";
result += " colors: Black, White, Red, Green, Blue, Yellow\r\n";
return result;
}

ScriptableClock.html
------------------------------
<html>
<head>
<title>Clock with Lots o' Widgets</title>
<script type="text/javascript">

function setTimeZone(popup) {
var choice = popup.options[popup.selectedIndex].value;
document.clock2.setTimeZone(choice);
}

function setColor(form) {
var bg = form.backgroundColor.options[
form.backgroundColor.selectedIndex].value;
var fg = form.foregroundColor.options[
form.foregroundColor.selectedIndex].value;
document.clock2.setColor(bg, fg);
}

function setFont(form) {
var fontName = form.theFont.options[form.theFont.selectedIndex].value;
var fontStyle = form.theStyle.options[
form.theStyle.selectedIndex].value;
var fontSize = form.theSize.options[form.theSize.selectedIndex].value;
document.clock2.setFont(fontName, fontStyle, fontSize);
}

function getAppletInfo(form) {
form.details.value = document.clock2.getInfo();
}

function showSource() {
var newWindow = window.open("ScriptableClock.java","",
"width=450,height=300,resizable,scrollbars");
}

</script>
</head>
<body>
<applet code="ScriptableClock.class" name="clock2"
width="500"
height="45">
<param name="bgColor" value="Black" />
<param name="fgColor" value="Red" />
</applet>
<form name="widgets2">
Select Time Zone: <select name="zone"
onchange="setTimeZone(this)">
<option selected="selected" value="Locale">Local Time</option>
<option value="GMT">Greenwich Mean Time</option>
</select>
<p>Select Background Color: <select name="backgroundColor"
onchange="setColor(this.form)">
<option value="White">White</option>
<option selected="selected" value="Black">Black</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Yellow">Yellow</option>
</select> Select Color Text Color: <select name="foregroundColor"
onchange="setColor(this.form)">
<option value="White">White</option>
<option value="Black">Black</option>
<option selected="selected" value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Yellow">Yellow</option>
</select></p>
<p>Select Font: <select name="theFont"
onchange="setFont(this.form)">
<option selected="selected" value="TimesRoman">Times
Roman</option>
<option value="Helvetica">Helvetica</option>
<option value="Courier">Courier</option>
<option value="Arial">Arial</option>
</select><br />
Select Font Style: <select name="theStyle"
onchange="setFont(this.form)">
<option selected="selected" value="Plain">Plain</option>
<option value="Bold">Bold</option>
<option value="Italic">Italic</option>
</select><br />
Select Font Size: <select name="theSize"
onchange="setFont(this.form)">
<option value="12">12</option>
<option value="18">18</option>
<option selected="selected" value="24">24</option>
<option value="30">30</option>
</select></p>
<hr />
<input type="button" name="getInfo" value="Applet Info"
onclick="getAppletInfo(this.form)" />
<p><textarea name="details" rows="11" cols="70">
</textarea></p>
</form>
<hr />
</body>
</html>

Here above it is only example, the classes you really need to use is
Socket Java class and emulate HTTP GET or POST or use simple Jakarta
HttpClient (see google).

Hope it helps.

BR
Luke M.

Apr 14 '06 #8

P: n/a
Thanks, the above example makes sense, the only question I have though
is about writting methods within the applet to get the site return
code. If I use 'simple Jakarta HttpClient' within the applet, then when
a call is made to a website for the status, would this call be from the
server, or client browser? I apoligize ahead of time as I am quite a
bit rusty with applets and have had no experience with Jakarta
HttpClient. All I want to accomplish is to gather the return codes from
several sites from the client browser experience. Thanks for your help!

Apr 14 '06 #9

P: n/a
Lasse Reichstein Nielsen said the following on 4/14/2006 6:54 AM:
Randy Webb <Hi************@aol.com> writes:
<URL: http://borkweb.com/story/look-ma-cross-domain-scripting >

I think a lot of that misunderstanding comes, in part, from that
website. It implies that JSON is the secret to it when it isn't. The
secret to it is dynamic script tags.


True. It's the Yahoo web-service format that uses JSON, but what it
sends is not pure JSON, but a function call with an argument that is a
JSON expression. It's good use of JSON, but it's not just that. It could
send any Javascript if it wanted, and it would still work as well.


Yes sir, Yes sir :)

Maybe we need something in the notes that covers just the non-JSON part
of it that can be referred to.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Apr 14 '06 #10

P: n/a
tr****@gmail.com wrote:
Thanks, the above example makes sense,
Unfortunately, there is no example above. Not even a minimized one.

<URL:http://jibbering.com/faq/faq_notes/pots1.html>
<URL:http://www.safalra.com/special/googlegroupsreply/>
the only question I have though is about writting methods within the
applet to get the site return code. If I use 'simple Jakarta HttpClient'
within the applet, then when a call is made to a website for the status,
would this call be from the server, or client browser? [...]


Applets are executed by the Java Runtime Engine on the client, if one is
installed and configured for the user agent. Servlets are executed by the
Java Runtime Engine on the server (hence the name). Both are _off topic_
here. Java != J(ava)Script/ECMAScript.

<URL:http://jibbering.com/faq/#FAQ2_2>
PointedEars
Apr 15 '06 #11

P: n/a

Thomas 'PointedEars' Lahn wrote:
Applets are executed by the Java Runtime Engine on the client, if one is
installed and configured for the user agent.
Applets are executed by Java Virual Machine provided by the Java
Runtime Envirnoment.
Servlets are executed by the
Java Runtime Engine on the server (hence the name).
Servlets are executed by the facto Servlet Container which is
executed by Java Virual Machine provided by Java Runtime Envirnoment
(or Java Development Kit) - part of Java 2 Standard Edition (SE).
Both are _off topic_
here. Java != J(ava)Script/ECMAScript.


They are not OFF TOPIC, simply becouse there is a touch between Java
Applets and JavaScript via LiveConnect (or something similar).

When you provide a link to faq entry or something else please provide
at least simple explanation or comment of lack of it (hence providing
link).

Best regards
Luke M.

Apr 16 '06 #12

P: n/a

tr****@gmail.com wrote:
If I use 'simple Jakarta HttpClient' within the applet, then when
a call is made to a website for the status, would this call be from the
server, or client browser?


Java Applets are executed within Java Virtual Machine, which is
started by the 'plugin' installed inside browser (hence the browser
must have JRE plugin installed). Applets appear inside html markup via
old but working everywhere <applet> tag or by <object> (see java
htmlconverter, but first install jre from java.sun.com). You need to
write one Java class with one method returning String, which will
contain status code of http get (since when you type url in address bar
and hit enter (or press Go or something similar), the browser really
makes HTTP GET URI). To make your life easier here is a code:

----------------------------------------------------------------------------------------

StatusCodeApplet.java
---------------------------------
package my.server.registered.url.or.something.else.package ; //just an
example

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class StatusCodeApplet
{
public String getStatusCode(String urlWithParams) {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(urlWithParams);
String returnStatusCode = "NO_STATUS_CODE";
try {
// Execute the method.
int statusCode = client.executeMethod(method);
// method.getStatusLine();
returnStatusCode = Integer.valueOf(statusCode).toString;
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " +
e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
return returnStatusCode;
}
}

StatusCodeApplet.html:
-----------------------------------
<html>
<head>
<title>Http status code demo</title>
</head>
<body>
<script type="text/javascript>
function getStatusCode(uri)
{
return document.applets['statusApplet'].getStatusCode(uri);
}
</script>
<applet name="statusApplet"
code="my.server.registered.url.or.something.else.p ackage.StatusCodeApplet.class"
width="0" height="0"
archive="commons-httpclient-3.0.jar"></applet>
</body>
</html>

----------------------------------------------------------------------------------------

StatusCodeApplet.class are made when you execute:

javac StatusCodeApplet.java -cp commons-httpclient-3.0.jar

, then you only need to put StatusCodeApplet.html,
commons-httpclient-3.0.jar and StatusCodeApplet.class on the same
location on your web server.

Hope it helps !

BR
Luke M.

Apr 16 '06 #13

P: n/a
Luke Matuszewski wrote:
Thomas 'PointedEars' Lahn wrote:
Applets are executed by the Java Runtime Engine on the client, if one is
installed and configured for the user agent.
Applets are executed by Java Virual Machine provided by the Java
Runtime Envirnoment.
Servlets are executed by the
Java Runtime Engine on the server (hence the name).


Servlets are executed by the facto Servlet Container which is
executed by Java Virual Machine provided by Java Runtime Envirnoment
(or Java Development Kit) - part of Java 2 Standard Edition (SE).


ACK
Both are _off topic_
here. Java != J(ava)Script/ECMAScript.


They are not OFF TOPIC,


Yes, usually they are. Therefore, you better had set Followup-To
comp.lang.java here.
simply becouse there is a touch between Java
Applets and JavaScript via LiveConnect (or something similar).
This subthread initiated by the OP's further question about your code was
not about LiveConnect/XPConnect (or something similar), hence my comment.
When you provide a link to faq entry or something else please provide
at least simple explanation or comment of lack of it (hence providing
link).


You want to leave it to me to decide how I point to further information,
thank you.
PointedEars
Apr 16 '06 #14

This discussion thread is closed

Replies have been disabled for this discussion.