【转】Calling Cross Domain Web Services in AJAX

(From: http://www.simple-talk.com/dotnet/asp.net/calling-cross-domain-web-services-in-ajax/)
( Joson:  Here is the most excellent article about cross-domain http request, so far as I searched.  And  some helpful comments attached.
    Before reading this article I've thought about dynamic script tag. For my developing requirement, in general way JSON parser format may not be the most limited condition. In order to post request, creating script tag ( sometimes destroying is also necessary? ) will spend many memory usage.
    Compared to flash cross-domain solution, which is better?
)

Calling Cross Domain Web Services in AJAX
29 December 2006

One of the current vogues in web applications is the creation of mashups. This involves the marrying of content and/or functionality from two different sources. Over the last few years, the opening up of formerly proprietary APIs from the likes of Google, Yahoo, Last.fm, Flickr, YouTube and Amazon has allowed developers to implement in their own applications, with simple one line calls to the requisite APIs, features such as adding photos, maps, booklists, videos and playlists.

The APIs allow the developer to select content through a series of filters such as location, date, user id, or membership of a particular group. The APIs are almost always thinly disguised wrappers for a web service.

With a lot of modern applications now employing Ajax techniques (with indeed whole web sites such as http://ajaxpatterns.org/ dedicated to Ajax patterns, and http://www.programmableweb.com/dedicated to mashup applications which utilize a lot of Ajax techniques), it makes sense to call the web services from within your own JavaScript. However, there is one big hitch to this theory. The XMLHttpRequest object is prevented from calling web services from outside its own domain. This is sensible given that if you called a script in one place and it, in turn, called a script on another server, it could leave an applicationopen to all sorts of malicious scripts, hacks and exploits.

However in the case of web services, it isn't so sensible. Web services are called with either SOAP or HTTP-GET/POST requests and return information in the same way. They are designed to be called from other domains, and in some ways it's an inherent contradiction to prevent them being called this way. So, given that there are plenty of mashups out there, and plenty of applications developed calling cross-domain web services, what do developers do to get around this limitation?

There isn't a single answer to this question, but in this article I'll discuss the current most popular techniques and what several developers are proposing to do get around this problem more neatly.

The XMLHttpRequest object

At the heart of the problem lies the XMLHttpRequest object. This object is central to many Ajax applications, although not an essential feature. The XMLHttpRequest object was introduced to IE5 as an ActiveX control, although the original version was conceived in Outlook Web Access 2000. This was an Outlook web-mail service that allowed people to access functionality such as download email, check calendars, and update contacts on the go, by allowing the application to issue its own client-side HTTP requests. It was introduced as a native object to Mozilla for release 1.0 and ended up in Safari 1.2 and Opera 7.60.

The XMLHttpRequest object doesn't allow calls to be made from code in one domain to a web service in another. The latest craze for mashups involves calling Web Services from APIs made publicly available by companies such as Google, Flickr, Yahoo, Last.fm and YouTube. This means that a call will always have to be made cross-domain, otherwise you can't use them. The best way to illustrate the problem is to build an example.

The currency converter example

In the example the application calls the freely available currency conversion services fromwebservicex.net. There are two drop down lists containing the list of currencies. So for example, you can select US Dollar in the first and Great British Pound Sterling in the second and then click on a button, to get the current rate. When the button is click, JavaScript is used to call the web service. The result is returned to the XMLHttpRequest object and ultimately rendered in the page.

Our application must have at least two sections, the first is the HTML page and the second is the script that calls the service. Our default.htm page is as follows:

<%@ Page Language="C#" 
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Ajax Currency Convertor</title>
<script type="text/javascript" src="Ajax.js"></script>
</head>
<body>
Currency To Convert From:
<select id="FromBox">
<option value="USD" selected="true">USD - U.S. Dollar</option>
<option value="GBP">GBP - British Pound</option>
<option value="EUR">EUR - Euro</option>
<option value="JPY">JPY - Japanese Yen</option>
</select>
Currency To Convert To:
<select id="ToBox">
<option value="USD">USD - U.S. Dollar</option>
<option value="GBP" selected="true">GBP - British Pound</option>
<option value="EUR">EUR - Euro</option>
<option value="JPY">JPY - Japanese Yen</option>
</select>
<br /><br />
<input id="button1" type="button" value="Click to convert currency"
onclick="initiateConversion()" />
<br /><br />
<table id="table1">
</table>
</body>
</html>

Our second section is the script IEAjax.js. If you create both of these items in Visual Studio, you'll be able to try this for yourself. Our application passes the web service URL straight to the XMLHttpRequest object using JavaScript code, via three functions:

function initiateConversion()
{
    xmlhttprequest = createRequestObject();
    var url = "http://www.webservicex.net/CurrencyConvertor.asmx/
ConversionRate?FromCurrency=?FromCurrency="
+ document.getElementByIdx_x_x_x("FromBox").value
+ "&ToCurrency="
+ document.getElementByIdx_x_x_x("ToBox").value ;
    xmlhttprequest.open("GET", url, true);
    xmlhttprequest.onreadystatechange = getData;
    xmlhttprequest.send(null);
}

function createRequestObject() 
{
        if (window.XMLHttpRequest) 
        {
                return xmlhttprequest = new XMLHttpRequest(); 
        } 
      else if (window.ActiveXObject) 
      {  
            return xmlhttprequest = new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
}
function getData() 
{
  if ((xmlhttprequest.readyState == 4) &&( xmlhttprequest.status == 200))
  {
    var myXml = xmlhttprequest.responseXML;
    var xmlobject = null;
    var XMLText = null;
    if (window.ActiveXObject)
    {
        XMLText = myXml.childNodes[1].firstChild.nodeValue; 
    }
    else
    {
        XMLText = myXml.childNodes[0].firstChild.nodeValue;
    }
    
    var table = document.getElementByIdx_x_x_x("table1");
    var row = table.insertRow(table.rows.length);
    var tablecell = row.insertCell(row.cells.length);
    tablecell.a(document.create_r_rTextNode
(document.getElementByIdx_x_x_x("FromBox").value
+ " to "
+ document.getElementByIdx_x_x_x("ToBox").value));
    var tablecell = row.insertCell(row.cells.length);
    tablecell.a(document.create_r_rTextNode(XMLText));
    table.setAttribute("border", "2");
  } 
}

The code starts with initiateConversion which creates an XMLHttpRequest object in the functioncreateRequestObject, then it sets the URL to point at the web service, and add two variables from the drop down list boxes, one for the "From" currency and one for the "To" currency. You call the open method of the XMLHttpRequest object, passing it the URL. You then prime theonreadystatechange event handler to run the getData function when a response is returned from the XMLHttpRequest object. The getData function receives the XML, extracts it (via the DOM), and injects it into a table.

【转】Calling <wbr>Cross <wbr>Domain <wbr>Web <wbr>Services <wbr>in <wbr>AJAX

Of course this code won't work by default due to the cross domain restrictions, so let's look at the simplest, but least satisfactory solution first.

Internet Explorer workaround

If you can be sure that your target audience will only be using Internet Explorer, and won't be too fussy about a security work-around, then there is an immediate solution available. You can add the site to your trusted sites, and reduce the security by enabling the "Access data sources across domains" option.

You can add a trusted site in IE via the Tools | Internet Options | Security tab. Then you can set the security for trusted site via the Custom level | Miscellaneous section. You'll see that, by default, the "Access data sources across domains" option is set to Prompt. However,Prompt is unsatisfactory because it will interrupt any current application that is running with a message box, asking the user to confirm that they want access to the service. Instead, set the option to Enable.

However, quite apart from the problem that each user of the application will need to configure IE before they can use it, Firefox doesn't even allow you to perform this workaround, and the default behavior of Firefox is not even to return an error. You'd have to check the error console to discover that an error had been raised, and to locate the source. So, as you can see, this is a far from universal solution.

Application proxies

A common theme of many of the solutions, instead, is getting JavaScript to call a proxy program (either on the client or the server) which, in turn, calls the web service for you. The output can be written to the response stream and then is available, via the normal channels, such as theresponseText and responseXML properties of XMLHttpRequest.

Flash – CrossDomain.xml

If you have a Flash application as part of the setup, then you can make use of an XML file that allow Flash applications to call web services, and which can be legally called. The Adobe site even specifies that one typical usage of crossdomain.xml is when

"a movie wishes to make a request to content hosted on a public server, such as web services, but is prohibited by the Flash Player cross-domain data access restrictions."

The crossdomain.xml file specifies other domains that can be called, and is placed at the root level of the application on any server to which the Flash movie player has access. You can then make the call to the web service via ActionScript.

An example Crossdomain.xml file is as follows:

<?xml version="1.0" ?> 
<cross-domain-policy>
<allow-access-from domain="*" /> 
<allow-access-from domain="*.macromedia.com" secure="false" /> 
<allow-access-from domain="*.adobe.com" secure="false" /> 
</cross-domain-policy>

Of course this technique depends on you using somewhere Flash in your application. Another drawback is that it only works with the most recent versions of Flash (version 7 onwards), so if one of these two criteria isn't met you will need another solution.

Server-side proxy

For the ASP.NET developer, probably the best solution is to load the XML content using ASP.NET and then return the content to the client side as pure XML. The downside of this is that you are adding an extra layer of indirection to your JavaScript code, and it requires you to have a server hosting ASP.NET to call on. Of course this is part and parcel of ASP.NET development, but if you have been developing your application only with JavaScript, then having IIS might not have been on your list of requirements.

In order to create an ASP.NET server side proxy, you have to amend your JavaScript code to add another layer of indirection. Instead of calling the web service directly, you now use theXMLHttpRequest object to call an ASP.NET page instead, and pass on any relevant variables.

Here is some sample JavaScript code:

var xmlhttprequest = null;
 
function initiateConversion()
{
    xmlhttprequest = createRequestObject();
    var url = "callservice.aspx?FromBox="
+ document.getElementByIdx_x_x_x("FromBox").value
+ "&ToBox="
+ document.getElementByIdx_x_x_x("ToBox").value ;
    xmlhttprequest.open("GET", url, true);
    xmlhttprequest.onreadystatechange = getData;
    xmlhttprequest.send(null);
}

In turn the ASP.NET code can load the URL as an XML document and then you can simply write the contents of the InnerXML property back to the response stream

       XmlDocument wsResponse = new XmlDocument();
        string url =  "http://www.webservicex.net/CurrencyConvertor.asmx/
ConversionRate?FromCurrency=" 
+ Request.QueryString["FromBox"].ToString()
+ "&ToCurrency="
+ Request.QueryString["ToBox"].ToString();
        wsResponse.Load(url);
        string XMLDocument = wsResponse.InnerXml;
        Response.ContentType = "text/xml";
        Response.Write(XMLDocument);

The JavaScript callback function getData remains unchanged from the previous section.

cURL proxy

If you have access to PHP – or alternatively can't use ASP.NET – then there is another alternative: you can use the cURL (client URL) library extensions in PHP. The JavaScript code can be amended as follows:

var path = 'http:// "http://www.webservicex.net/CurrencyConvertor.asmx/
ConversionRate?FromCurrency='
+ document.getElementByIdx_x_x_x("FromBox").value
+ "&ToCurrency="
+ document.getElementByIdx_x_x_x("ToBox").value;
var url = 'http://localhost/curl_proxy.php?ws_path='
+ encodeURIComponent(path);
xmlhttp.open('GET', url, true); 
 

Your PHP code makes the call on behalf of the JavaScript, by adding the hostname to your URL, and using the cURL to perform the invocation of the web service. Although we're passing the query string to the PHP code, it can accept the data as either a GET or a POST request:

define ('HOSTNAME', 'http://www.webservicex.net/');
 
$path = ($_POST['ws_path']) ? $_POST['ws_path'] : $_GET['ws_path'];
$url = HOSTNAME.$path;
 
// Open the Curl session
$session = curl_init($url);
 
if ($_POST['ws_path']) {
     $postvars = '';
     while ($element = current($_POST)) {
          $postvars .= key($_POST).'='.$element.'&';
          next($_POST);
     }
     curl_setopt ($session, CURLOPT_POST, true);
     curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
}
 
// Return the call not the headers
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
 
// call the data
$xml = curl_exec($session);
 
header("Content-Type: text/xml");
 
echo $xml;
curl_close($session);

The principle is the same as the ASP.NET code; the proxy opens a request to the web service for us and returns the response as XML. The XML is written to the response stream where it can be picked up by the XMLHttpRequest object.

Dynamic Script Tag hack

If you have a web service that returns JSON (JavaScript Object Notation format), then another option is open to you. You can dynamically create a script tag and assign the src attribute to the location of the web service. This will only work if the web service can return JSON, which is a format for data exchange based on a subset of JavaScript. JSON cannot represent functions or expressions; it can only represent data. It can be easily converted into a JavaScript value, and so is easy to reference via a script.

Unfortunately the Currency Conversion web service of webservicex.net doesn't offer this option. However all of the Yahoo Web services currently return JSON and one such example is theImageSearchService. This is a simple "Image Search Engine", whereby you supply the name of the person (or item) of whom you photographs and it will return an object for each "hit".

For example, the following URLS (web service calls) can be used to retrieve a list of all the images of Einstein on the web:

http://api.search.yahoo.com/ImageSearchService/V1/
   imageSearch?appid=YahooDemo&query=Einstein&output=json

and:

http://api.search.yahoo.com/ImageSearchService/V1/
   imageSearch?appid=YahooDemo&query=Einstein&output=
      json&callback=ws_results

It's possible, in a few lines of code, to add this call to an Ajax application to create an image search engine so that whoever you type the name of, it will return the first 10 images it finds on the Web in order. Our HTML/ASPX page would look as follows:

<%@ Page Language="C#"  
CodeFile="Dynamic.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Dynamic Script Tag Example</title>
<script type="text/javascript" src="ajax2.js"></script>
</head>
<body>
Find Images:
<input id="userinput" type="text" />
<input type="button" onclick="dynamicTag();" value="Search" />
<br />
<div id="PlaceImages"></div>
</body>
</html>

When the button is clicked, we make the call to the JavaScript function, dynamicTag, which dynamically creates a <script> element. This script element has no src attribute, so we dynamically create one and we assign the src attribute's URL as a call to the web service, so that when the page is opened, the web service is automatically called.

function dynamicTag()
{
    var userinput = document.getElementByIdx_x_x_x("userinput").value;
    var request = "http://api.search.yahoo.com/ImageSearchService/V1/
imageSearch?appid=YahooDemo&query="
+ userinput
+ "&output=json&callback=getImages";
    var head = document.getElementsByTagName_r("head").item(0);
    var script = document.create_r_rElement_x("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", request);
    head.a(script);
}

We pass as a parameter to our web service the value the user supplied to the text box. We also specify that the output should be JSON in the parameters, and the name of the callback function that the thread of execution should pick up at when control is returned to the client. The callback function is as follows:

function getImages(JSONData) {
    if (JSONData != null)
    {
      var div = document.getElementByIdx_x_x_x("PlaceImages");
      for (i=0; i<10; i++)
      {
        var image = document.create_r_rElement_x("image");
        image.setAttribute("src", JSONData.ResultSet.Result[i].Url);
        image.setAttribute("width", 100);
        image.setAttribute("height", 100);
        div.a(image);
      }
    }
}

The JSONData object has a ResultSet format, which returns a separate object for each result that is returned. The object returns Title, Summary, Url, ClickUrl, RefererUrl, FileSize,FileFormat, Height, Width and Thumbnail properties. So, for the first item in our ResultSet in the example, the properties would be returned as follows:

Title: "einstein.jpg"
    Summary: "Selon Einstein, 98 % de la population ne serait pas capable
de résoudre l'énigme suivante. Ferez-vous partie des 2 %
les plus intelligents ? A vous de"
    Url: "http://www.ac-creteil.fr/Colleges/93/jmoulinmontreuil/
mathematiques/enigmes/anciennes_enigmes2/gifs/einstein.jpg"
    ClickUrl: "http://www.ac-creteil.fr/Colleges/93/jmoulinmontreuil/
mathematiques/enigmes/anciennes_enigmes2/gifs/einstein.jpg"
    RefererUrl: "http://www.ac-creteil.fr/Colleges/93/jmoulinmontreuil/
mathematiques/enigmes/anciennes_enigmes2/enigme24.htm"
    FileSize: "25828"
    FileFormat: "jpeg"
    Height: "291"
    Width: "281"
    Thumbnail: {...}

The application then dynamically creates an image and assigns the URL property as the srcattribute. We loop through for the first 10 images displaying each to the page as follows:

【转】Calling <wbr>Cross <wbr>Domain <wbr>Web <wbr>Services <wbr>in <wbr>AJAX

There are several disadvantages to this technique, though. This solution is reliant on JSON and so excludes quite a few web services that don't have a JSON option. Also, when you use dynamic scripts, you can't tell if the script had loaded correctly or not, as there is no return from the script; either it works or it doesn't. A further problem is that, in IE, the dynamic loading of scripts stops all other processing. Most seriously, using this technique with Internet IE5 and IE6 causes a potential memory leak.

Future directions

If you find none of these solutions completely satisfying, and feel that they all involve hacks or incomplete solutions, then you're not alone here: so do I. There are a lot of ifs and buts involved, and your choice of solution will often be dictated not by what is best, but what is available to you.

As a consequence there are several other solutions being proposed by different developers and it's worth taking a brief look at each.

FlashXMLHttpRequest

This is a project by Julian Couvreur, which leverages the existing crossdomain.xml files but instead uses a FlashXMLHttpRequest proxy. This is already in beta, although several links to it are now dead. It uses a small SWF file to make GET and POST requests on your behalf.

The reason that this is more interesting than just using crossdomain.xml is that this object, in addition, has SWF versions that support earlier versions of Flash and enables almost any browser (that has Flash installed) to make use of the Crossdomain.xml files.

The FlashXMLHttpRequest object has some limitations, (placed upon it by the version of Flash it is using), such as not being able to send or receive HTTP status codes or headers, or handle HTTP Puts and Deletes. It's a pity that links to the beta were dead at the time of publication of this article, because the proposal is an interesting one.

ContextAgnosticXMLHttpRequest

Chris Holland's proposal at:

http://chrisholland.blogspot.com/2005/03/contextagnosticxmlhttprequest-informal.html

involves creating a second object, ContextAgnosticXMLHttpRequest, which would be used instead of the XMLHttpRequest in situations that involve cross domain calling.

The ContextAgnosticXMLHttpRequest object would be able to pass security details to the application allowing the application permission to call up specific services in other domains. This proposal runs in tandem with debate from other developers, and Microsoft, who propose passing an extra HTTP Header, which is notionally called "X-Allow-Foreign-Hosts." TheContextAgnosticXmlHttpRequest object would not expose any data from a service without this header.

This proposal is no further forward than the informal RFC stage, but indicates that many people are thinking along similar lines.

JSONRequest

Last is JSONRequest which is Doug Crockford's proposal at http://json.org/JSONRequest.html.

He proposes a new browser service that will initiate a two-way data exchange between the browser and a JSON data server. This relies on future versions of browsers incorporating this facility into the browser.

Doug proposes the creation of a new object, JSONRequest (not to be confused with the one we created earlier), which can initiate GET, POST or CANCEL requests. The data that is sent and received via the object is serialized into the JSON format by the web service, The object would be restricted to using JSON encoded values.

As the proposal excludes the use of cookies or passwords, it neatly avoids the problems of the browser being given false authorization. It looks perhaps the most promising of the three alternatives, given that JSON is already being viewed as a possible alternative to XML in some situations. It also confers certain benefits such as being simpler, more readable and better suited to data exchange, as opposed to document exchange which is what XML deals in.

Conclusion

There is no one perfect way to call web services cross domain using Ajax. Currently I rely on an ASP.NET server-side proxy as a solution; although ultimately a solution involving JSON looks to be preferable. As things stand you are not supposed to be able call a web service cross domain using Ajax and any attempt to do so involves some sort of hackery or underhandedness. However if web services popularity is to continue to prosper, then a de-facto solution will have to emerge, and more likely than not, it will have come from the dusty backrooms of developers, rather than as the latest add-on from the browser makers.



This article has been viewed 99584 times. Chris Ullman

Author profile: Chris Ullman

Chris Ullman is a freelance web developer and technical author who has spent many years stewing in ASP/ASP.NET, like a teabag left too long in the pot. Coming from a Computer Science background, he gravitated towards MS technologies during the summer of ASP (1997). Since then he has written on over 25 books, most notably as lead author for Wrox's best-selling Beginning ASP/ASP.NET 1.x/2 series. After leaving Wrox as a full time employee in August 2001, he branched out into VB.NET/C# programming and ASP.NET development and started his own business CUASP Consulting Ltd. in April 2003. He maintains a variety of sites from http://www.cuasp.co.co.uk, his "work" site, to http://www.atomicwise.com, a selection of his writings on music and art.

Search for other articles by Chris Ullman



Subject:document.domain
Posted by: Steven (not signed in)
Posted on:Friday, January 05, 2007 at 8:09 AM
Message:By no means a solution to the wider problem, but would relaxation of the document.domain attribute in the page allow intranet cross-site AJAX?

e.g. document.domain = www.simple-talk.com could be relaxed to simple-talk.com and then an AJAX call could be made to api.simple-talk.com

Would that work? Would that have worked anyway?

This could also allow a company to run a single proxy that all of its websites on whichever server could use to call out to other sites?


Subject:Dojo has a solution
Posted by: Yash Sharma (not signed in)
Posted on:Friday, January 12, 2007 at 3:59 AM
Message:Dojo has something called an iFrameProxy, but it requires the API host to have a file xip_server.htm hosted

Subject:Great article on calling webserves across domains
Posted by: Anonymous (not signed in)
Posted on:Monday, April 02, 2007 at 3:27 PM
Message:Thanks Chris for sharing your insight on this XMLHttpRequest object cross domain behavior. I’ve been testing access via AJAX of a WebService on my development machine from a web application on my development machine, using variations of (localhost, machine_name, IP_Address). Only to find that all resources, WebService and the calling web page must share the identical domain reference in order to access the WebService without error. This security wall imposed by the XMLHttpRequest object seems to not be well documented. In any case, I knew right after finding your article here that I had finally found the culprit preventing my cross domain access. A quick addition of http://localhost to my IE trusted sites list immediately proved it. Your article is very concise and well written.

Thanks again,

Lew

LewChaney@Yahoo.com


Subject:Internet Explorer workaround
Posted by: William (view profile)
Posted on:Friday, July 20, 2007 at 3:23 PM
Message:Hi Chris,

An excellent article.

I tried to apply the solution of the section "Internet Explorer workaround" but it did not work to me because I am using Apache, only works with IIS.

Subject:Internet Explorer workaround
Posted by: William (view profile)
Posted on:Friday, July 20, 2007 at 3:34 PM
Message:Hi Chris,

An excellent article.

I tried to apply the solution of the section "Internet Explorer workaround" but it did not work to me because I am using Apache, only works with IIS.

Subject:great article
Posted by: Milosz (not signed in)
Posted on:Friday, July 27, 2007 at 7:07 AM
Message:Hi,
big thanks for this article - it really saved me a lot of time and thinking on how to deal with a ajax-remote-server call I was supposed to make.
Thanks a lot!
Miłosz

Subject:you may missed something - its the curl for windows
Posted by: remiglobal (not signed in)
Posted on:Sunday, September 02, 2007 at 1:13 AM
Message:i may have implement something like this. you can install curl for windows and install the related library. just go to http://curl.haxx.se

Subject:Server side proxy
Posted by: jappenzeller (not signed in)
Posted on:Monday, October 15, 2007 at 10:28 AM
Message:I tried the server side proxy with .net method and I still get the access denied message. Does the xmlhttprequest object only block with asmx pages?

Subject:Nevermind
Posted by: Jappenzeller (not signed in)
Posted on:Monday, October 15, 2007 at 10:39 AM
Message:Nevermind my previous post, i just realized what the server side proxy meant. duh.

Subject:Neat xplain
Posted by: jackwenttohill (not signed in)
Posted on:Friday, January 11, 2008 at 6:38 AM
Message:Clear my doubts! Thanks.

Subject:GOOd Article But
Posted by: ibrahim (view profile)
Posted on:Sunday, April 20, 2008 at 1:42 PM
Message:How can make this work on Firefox???

Subject:If only I saw this article before ...
Posted by: nativebreed (view profile)
Posted on:Thursday, October 09, 2008 at 9:05 AM
Message:After 3 hrs of messing around trying to solve my AJAX cross-domain issue for our currency converter service at http://currencyconverter.55uk.net - finally decided JSON was the way to go - the same way, Yahoo uses to deliver services.

Will it ever be easy to AJAX across domains? or is the security risk too great?

Subject:Neat Explanation on JSON, however...
Posted by: efaizal (view profile)
Posted on:Friday, November 14, 2008 at 6:28 PM
Message:Just a small issue that needs to be addressed. I tried the JSON technique, but it does not work the first time I tried it.

There is an "error" (no warning or error message generated) in javascript function getImages(JSONData){...}

Instead of:
var image = document.create_rElement("image");

Use:
var image = document.create_rElement("img");

Also, in javascript function dynamicTag(){...} function,

the var request = "http://api.search.yahoo.com/... cannot be in multiple line.

Thank you

Subject:flXHR for better cross-domain Ajax with flash
Posted by: shadedecho (view profile)
Posted on:Monday, April 20, 2009 at 8:51 AM
Message:This is a really good article, I was please to see the various options laid out in such a good organized fashion.

I have a project called flXHR http://flxhr.flensed.com which is similar to some of the cross-domain ajax with flash solutions mentioned here, but goes one step further: flXHR implements an identical API to the native XHR object, which means it can be dropped into any existing project with almost no code changes necessary, and you automagically will get cross-domain Ajax capability.

Subject:Best Information
Posted by: abhijitaitwade (view profile)
Posted on:Friday, April 02, 2010 at 6:06 AM
Message:I m searching for this information. I got it.

It's helpfull
Thanks.
DVWA靶场实战:从原理到防御,彻底掌握CSRF跨站请求伪造 跨站请求伪造是一种常见的Web安全威胁,其核心原理是攻击者利用用户已认证的会话状态,诱骗浏览器向目标网站发起非本意的恶意请求。从技术实现上看,它利用了浏览器对Cookie等凭证的自动携带机制,在用户无感知的情况下执行敏感操作,如修改密码或发起转账。这种攻击的价值在于其极高的隐蔽性和破坏性,常被用于身份冒用和业务逻辑篡改。在应用场景上,任何依赖会话状态且缺乏足够防护的Web交互都可能存在风险,例如论坛发帖、资料修改或金融交易。本文以DVWA靶场为实验环境,通过手把手复现攻击过程,深入剖析了同步令牌、双重Coo 阅读详情

相关推荐

Ubuntu 16.04 搭建 ownCloud 私有云:LAMP 部署实战指南

私有云是实现数据自主可控的核心基础设施,其本质是基于 Web 技术栈构建的、可本地化部署与管理的协作存储系统。原理上依赖 LAMP(Linux-Apache-MySQL-PHP)经典组合,通过 Apache 处理 HTTP 请求与重写、MySQL 持久化结构化数据、PHP 承载业务逻辑,三者协同保障文件同步、WebDAV 访问与权限控制等关键能力。该架构技术价值在于零外部依赖、配置透明、故障可溯,显著降低合规风险与运维复杂度。典型应用场景包括自由职业者数据归档、律所客户资料管理、高校教学资源共享,以及 PH

weixin_30772105的博客 529

Cross-Domain on Jersey RESTful Web Services

Jersey is based on JAX-RS Java community standard, and quite convenient for implementing a RESTful Web Services to serve various flavors of calls in backend. In general, we may use the JSONP workaroun

Inzghi的专栏 1336

Apache服务器本质:模块化HTTP服务编排平台

Web服务器是支撑网站运行的基础网络服务,其核心在于处理HTTP请求与响应。Apache作为历史悠久的开源实现,以模块化架构、配置驱动和多进程/线程模型为技术底座,提供高度可定制的协议处理能力。它不追求极致并发,而强调稳定性、可审计性与细粒度控制,广泛应用于金融、政务等对合规与可靠性要求严苛的场景。通过MPM模型适配不同负载、mod_rewrite实现请求路由编程、mod_ssl集成现代TLS实践,Apache已从传统Web服务器演进为云原生环境中的可信协作组件。本文深入解析其请求生命周期、模块协同机制与生

chuji3953的博客 342

Cross-Domain AJAX Enabled WCF Service

Background For the basic of how to create an AJAX enabled WCF service, please refer to MSDN: http://msdn.microsoft.com/en-us/library/bb924552.aspx. For the basic of JSONP, please refer to: http:/

Teddy's Knowledge Base 1979

Docker部署Nextcloud私有云:MariaDB、OnlyOffice与HTTPS全栈实践

Nextcloud作为主流开源私有云平台,其稳定部署依赖Docker容器化、MariaDB数据库优化、OnlyOffice在线协作集成及HTTPS安全加固四大核心技术。理解Docker Compose服务健康检查机制与依赖等待原理,可避免因启动时序导致的500/404错误;掌握MariaDB字符集配置与InnoDB参数调优,是保障Nextcloud全文搜索与大文件上传可靠性的底层基础;而OnlyOffice的JWT兼容性控制与Nginx路径重写规则,则直接决定文档协同功能是否可用。在家庭NAS、边缘服务器或

weixin_30328063的博客 520

Virtuoso ADE Explorer实战技巧:从基础操作到高级仿真

本文深入解析了Virtuoso ADE Explorer在模拟电路仿真中的核心价值与实战技巧。作为Cadence平台的专业工具,它专为高效、系统化的设计空间探索而生,能大幅提升PVT验证、参数扫描和蒙特卡洛分析的效率。文章从基础界面操作、并行仿真管理,到高级的参数扫描、数据报告生成及蒙特卡洛结果深度剖析,提供了全面的避坑指南与工作流优化建议,帮助工程师从重复劳动中解放,专注于电路设计与性能优化。

ios99的博客 916

{{js跨域请求解决方案}}Use a Web Proxy for Cross-Domain XMLHttpRequest Calls(使用服务器端代理实现Ajax跨域请求)

JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls 综述: XMLHttpRequest同域限制只是浏览器端的安全限制,但是服务器端并没有同域安全限制,故可以通过服务器端来实现跨域请求,然后在浏览器端通过Ajax获取服务器端的跨域请求的数据,这就是所谓的在服务器端建立一个XMLHttpRequest代理,通过这个代

香巴拉 2245

Arcgis填补栅格空缺值Nodata

Arcgis填补栅格空缺值Nodata

pass17的博客 1万+

{{js跨域请求解决方案}}Use a Web Proxy for Cross-Domain XMLHttpRequest Calls(使用服务器端代理实现Ajax跨域请求)...

JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls 综述: XMLHttpRequest同域限制只是浏览器端的安全限制,但是服务器端并没有同域安全限制,故可以通过服务器端来实现跨域请求,然后在浏览器端通过Ajax获取服务器端的跨域请求的数据,这就是所谓的在服务器端建立一个XMLHttpRequest代理,通过这...

WEBCODE 376

告别CNN局限:用Transformer+迁移学习搞定高光谱图像分类(附Pytorch代码)

本文探讨了如何利用Transformer的自注意力机制和迁移学习策略解决高光谱图像分类中的挑战。通过结合CNN的局部特征提取和Transformer的全局建模能力,提出的DenseTransformer架构在多个数据集上实现了显著的性能提升。文章还提供了详细的PyTorch实现代码和工程优化技巧,帮助开发者快速应用这一技术。

weixin_32771907的博客 625

Mamba SSM 实战:IMDb 文本分类 + Mamba-ssm 全流程

Mamba SSM 文本分类链路:IMDb 二分类 → MambaLMHeadModel (d_model=256, n_layer=8, d_state=16, exp2=2) → 末 token 分类头。5 epoch 达 89.2% 准确率 (与 BERT-base 持平), 但显存降低 44% (3.5GB vs 6.2GB)。建议序列长度 ≥ 1024 再选 Mamba, 短序列 (< 512) 用 BERT 更高效。扩展时注意d_state。

m0_71589036的博客 62

20210308某区块链公司前端面试总结

目录 讲下数组的一些方法 跨域的处理方式 讲下你最近的项目 setState到底是异步还是同步 讲下hooks 讲下react的性能优化 前端的通信方式 讲下webpack的构建流程 1. 讲下数组的一些方法 比如:concat,fill,filter,map,pop,push,shift,slice,some,sort,includes等。 2. 跨域的处理方式 跨域主要分3部分: 协议相同 域名相同 端口相同 只要有一个不同,那么就是跨域 // 地址 http://www.baidu.

uperficialyu的博客 1521

beegfs读取文件完整流程分析

读取小于512KB文件数据,小于1s 读取15MB文件数据,花费7秒。

wfzy的博客 842

前端跨域的七种解决方案

前端开发的历史年轮 服务端渲染 客户端渲染(同源策略) 客户端渲染(跨域方案) 半服务端渲染(SSR) 谈谈你对跨域的理解 跨域主要分3部分: 协议相同 域名相同 端口相同 只要有一个不同,那么就是跨域 // 地址 http://www.baidu.com 协议:http:// 域名:www.baidu.com 端口:8080(http) 443(https) 默认端口省略 http://www.baidu.com/login.html // 同源 http://w

uperficialyu的博客 876

全面指南:PyTorch与ROCm版本兼容性及多版本环境管理

本文详细介绍了在AMD GPU上配置PyTorch开发环境的完整流程,重点解决版本兼容性和多版本ROCm环境管理问题。主要内容包括:1) PyTorch与ROCm版本对应关系查询;2) 四种查看ROCm版本的方法;3) 使用update-alternatives管理多版本ROCm;4) 环境变量配置与冲突解决方案;5) 完整的验证流程和性能测试方法。文章提供了最佳实践建议和故障排除清单,帮助开发者快速搭建稳定高效的深度学习开发环境,充分发挥AMD GPU硬件性能。通过系统化的验证流程确保各组件协同工作,解决

数字人生 609

100天精通Python(可视化篇)——第80天:matplotlib绘制不同种类炫酷柱状图代码实战(簇状、堆积、横向、百分比、3D柱状图)

0. 专栏导读 1. 普通柱状图 2. 簇状柱形图 3. 堆积柱形图 4. 横向柱状图 5. 横向双向柱状图 6. 百分比堆积柱形图 7. 3D柱形图 8. 3D堆积柱形图 9. 3D百分比堆积柱形图

努力让自己发光,对的人才能迎着光而来 2万+

【转】DNS协议报文(RFC1035)

(转自:http://hi.baidu.com/wzypunk/blog/item/1fb46d26fb4130fcd6cae22e.html)DNS协议报文(RFC1035) 2010-10-16 17:19 一、域名和资源记录的定义 1、Name space definitions2、资源记录定义(RR definitions)    2.1 格式         后面分析报文...

837

从 AI 助手到 ADT 自动化桥梁:全面解析 Vibing Steampunk 的定位、能力边界与典型使用场合

Vibing Steampunk是一个面向SAP ABAP开发的AI自动化工具集,它通过ADT API将SAP开发能力系统化地暴露给AI助手和命令行工作流。该工具支持ECC、S/4HANA等所有启用ADT的系统,提供代码读取、修改、测试、调试等全流程自动化能力。核心功能包括AI调试、上下文压缩、ABAP语言服务、Lua脚本自动化等,并内置多重安全控制。其分层架构兼容标准ADT和WebSocket扩展,既适合AI驱动开发,也支持传统DevOps自动化,特别适用于老系统代码考古、知识接力和复杂问题诊断场景。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 158

Table单元格td的position:relative的兼容性

( From:  http://www.itref.cn/a/css/2010/0706/70.html)问题描述: 默认情况下,table的单元格td的display为table-cell,在IE给td设置position:relative,然后给它包含的一个容器使用position:absolute进行定位是有效的,但在FF下却不可以。但是在IE下,position:absolute的容器的...

735

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

HTTP Status Code

(From: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)part of Hypertext Transfer Protocol -- HTTP/1.1RFC 2616 Fielding, et al. 10 Status Code Definitions Each Status-Code is described below...

415

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

【转】DNS报文格式

(转自:http://hi.baidu.com/hcq11/blog/item/5e3a1bed2ef1ced8b21cb179.html/cmtid/3d8f1b9074f6cb80a877a4f6) 总结:DNS报文格式 2010-04-08 10:13 DNS报文格式(借个图贴过来):     说明一下:并不是所有DNS报文都有以上各个部分的。图中标示的“12字节”...

324

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

HTTP multipart/form-data 上传方式说明

  ( From: http://home.meegoq.com/home-space-do-blog-uid-17-id-81.html ) HTTP multipart/form-data 上传方式说明 已有 123 次阅读 2010-12-1 11:13 |个人分类:网络学习|关键词:HTTP multipart http上传文件方面的功能使用的协议是rfc1867 (ht...

292

(转)UPNP协议细节

(From: http://www.cnblogs.com/semo/archive/2008/07/21/1247950.html)UPNP的全称是 Universal plug-and-play( 通用即插即用).UPnP 是针对智能家电、无线设备以及各种外观尺寸的个人电脑的普遍对等(peer-to-peer)网络连接而设计的一种架构。它旨在为家庭、小型企业、公共场 所中或连接到互联网的ad-...

237

[转] HTTP multipart/form-data 上传方式说明

( From: http://home.meegoq.com/home-space-do-blog-uid-17-id-81.html ) HTTP multipart/form-data 上传方式说明 已有 123 次阅读 2010-12-1 11:13 |个人分类:网络学习|关键词:HTTP multipart http上传文件方面的功能使用的协议是rfc1867 (http...

235
上一篇: Which browsers support HTML5, CSS3, Data URLs, etc.
下一篇: Relying on DOM readiness to invoke a function (instead of window.onload)
excpp
博客等级 码龄15年 0粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址