使用JQuery进行跨域请求
作者:bea
以上程序是今天偶然看到的,分享一下! 原文地址: Cross-domain-request-with-jquery 当然,还有以上的那个 Demo,我直接拿过来改了下,原地址: Demo 代码如下: $(document).ready(function(){ var container = $('#target'); container.attr('tabIndex','-1'); $('.ajaxtrigger').click(function(){ var
以上程序是今天偶然看到的,分享一下!
原文地址:
Cross-domain-request-with-jquery
当然,还有以上的那个 Demo,我直接拿过来改了下,原地址:
Demo
代码如下:
$(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('<span></span>');
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%20*%20from%20html%20where%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 = '<p>Error: could not load the page.</p>';
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(/<?/body[^>]*>/g,'');
// no linebreaks
data = data.replace(/[ |
]+/g,'');
// no comments
data = data.replace(/<--[Ss]*?-->/g,'');
// no noscript blocks
data = data.replace(/<noscript[^>]*>[Ss]*?</noscript>/g,'');
// no script blocks
data = data.replace(/<script[^>]*>[Ss]*?</script>/g,'');
// no self closing scripts
data = data.replace(/<script.*/>/,'');
// [... add as needed ...]
return data;
}
});
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- javascript让setInteval里的函数参数中的this指向特定的对象
- 详细讲解JS节点知识
- javascript中的array数组使用技巧
- jquery 批量上传图片实现代码
- Jquery 常用方法经典总结
- javascript 匿名函数的理解(透彻版)
- JavaScript 学习笔记(十五)
- Extjs 几个方法的讨论
- JavaScript 判断判断某个对象是Object还是一个Array
- 图像替换新技术 状态域方法
- javascript innerText和innerHtml应用
- js 右键菜单,支持不同对象不同菜单(兼容IE、Firefox)
- 使用JavaScript库还是自己写代码?
- js或css实现滚动广告的几种方案
- jquery中的sortable排序之后的保存状态的解决方法
- javascript面向对象的方式实现的弹出层效果代码
- js提示信息jtip封装代码,可以是图片或文章
- jquery 常用操作方法
- jquery 经典动画菜单效果代码