Ajax example Tutorial: How to Solve ajax cross-origin problems

Source: Internet
Author: User

To solve cross-origin ajax problems, the following methods are provided on the Internet:

1 is to build a server-side proxy. In short, it means that the essence of ajax calls is the local url, and the server side retrieves the remote address for js.

2. Generate a tag using the script tag. After loading js, perform subsequent operations.

That is, the new xmlHTTPrequest object operation is changed to the new script tag operation.

Here is an example:

# Ajah. js

Var Ajah = function (url, varname, handleSuccess, handleFailure ){
/**
* HandleSuccess, handleFailure must be functions
**/
Script = document. createElement ("script ");
Script. src = url;
Var handler = function (str)
{
HandleSuccess (str );
}
Script. onload = function ()
{
Var json = eval (varname );
Handler (json );
}
If (window. ie)
{
Script. onreadystatechange = function ()
{
If (script. readyState = 'complete' | script. readyState = 'loaded ')
{
Var json = eval (varname );
If (typeof json! = 'Undefined ')
{
Handler (json );
}
}
}
}
Document. body. appendChild (script );
}

In the web page, you should call the following method:

Includemo.html

<Pre>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 3.2 // EN">
<Html>
<Head>
<Meta name = "generator" content =
"HTML Tidy for Linux (vers 1 September 2005), see www.w3.org">

<Title> </title>
<Script src = "mootools. js"> </script>
<Script src = "ajah. js"> </script>
</Head>

<Body>
<Script>
Var ajah = new Ajah ("data. js", "json198", function (str ){
Console. debug ("returned :");
Console. debug (str );
},
Function (str ){});
</Script>
</Body>
</Html>
</Pre>

The called data file is as follows:

# Data. js

Var json198 = "hello, this is json198 ";
Funciton Ajah (url, varname, handleSuccess, handleFailure ){...}
The Ajah constructor calls four parameters:
Url: Remote address
Varname: variable name of the remote returned data
HandleSuccess: function loaded after loading
HandleFailure: Temporarily unavailable

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.