Home  >  Article  >  Web Front-end  >  Using JQuery for cross-domain requests_javascript tips

Using JQuery for cross-domain requests_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:35:571019browse
I saw the above program by chance today, share it with me!
Original address: Cross-domain-request-with-jquery
Of course, there is also the above Demo. I took it directly and changed it. The original address: Demo

Copy code 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::last');
} else {
var msg = trigger.find('span::last' );
}
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 * from html where url=" "
encodeURIComponent(url)
""&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 = '< ;p>Error: could 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(/<- -[Ss]*?-->/g,'');
// no noscript blocks
data = data.replace(/]*>[Ss]* ?/g,'');
// no script blocks
data = data.replace(/]*>[Ss]*?/g,'');
// no self closing scripts
data = data.replace(//,'');
// [.. . add as needed ...]
return data;
}
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn