JQuery implements the cross-origin Request Code. For more information, see. The above program was accidentally seen today. Share it with me! Original article address: Cross-domain-request-with-jquery, of course, there is also the Demo above, I directly changed it, the original address: Demo
The Code is as follows:
$ (Document). ready (function (){
Var container = $ ('# target ');
Container. attr ('tabindex', '-1 ');
$ ('. Ajaxtrigger'). click (function (){
Var trigger = $ (this );
Var url = trigger. attr ('href ');
If (! Trigger. hasClass ('loaded ')){
Trigger. append ('');
Trigger. addClass ('loaded ');
Var msg = trigger. find ('span: la ');
} Else {
Var msg = trigger. find ('span: la ');
}
DoAjax (url, msg, container );
Return false;
});
Function doAjax (url, msg, container ){
// If the URL starts with http
If (url. match ('^ http ')){
// Assemble the YQL call
Msg. removeClass ('error ');
Msg.html ('(loading ...)');
$. GetJSON ("http://query.yahooapis.com/v1/public/yql? "+
"Q = select % 20 * % 20 from % 20 html % 20 where % 20url % 3D % 22" +
EncodeURIComponent (url) +
"% 22 & format = xml' & callback =? ",
Function (data ){
If (data. results [0]) {
Var data = filterData (data. results [0]);
Msg.html ('(ready .)');
Container.
Html (data ).
Focus ().
Effect ("highlight", {}, 1000 );
} Else {
Msg.html ('(error !) ');
Msg. addClass ('error ');
Var errormsg ='
Error: cocould not load the page.
';
Container.
Html (errormsg ).
Focus ().
Effect ('highlight', {color: '# c00'}, 1000 );
}
}
);
} Else {
$. Ajax ({
Url: url,
Timeout: 5000,
Success: function (data ){
Msg.html ('(ready .)');
Container.
Html (data ).
Focus ().
Effect ("highlight", {}, 1000 );
},
Error: function (req, error ){
Msg.html ('(error !) ');
Msg. addClass ('error ');
If (error = 'error') {error = req. statusText ;}
Var errormsg = 'There was a communication error: '+ error;
Container.
Html (errormsg ).
Focus ().
Effect ('highlight', {color: '# c00'}, 1000 );
},
BeforeSend: function (data ){
Msg. removeClass ('error ');
Msg.html ('(loading ...)');
}
});
}
}
Function filterData (data ){
// Filter all the nasties out
// No body tags
Data = data. replace (/ ] *>/G ,'');
// No linebreaks
Data = data. replace (/[\ r | \ n] +/g ,'');
// No comments
Data = data. replace (/<-- [\ S \ s] *? -->/G ,'');
// No noscript blocks
Data = data. replace (/ ] *> [\ S \ s] *? <\/Noscript>/g ,'');
// No script blocks
Data = data. replace (/ ] *> [\ S \ s] *? <\/Script>/g ,'');
// No self closing scripts
Data = data. replace (/ /,'');
// [... Add as needed...]
Return data;
}
});