在不使用jQuery或其他外部库的情况下,是否可以在JavaScript中发出跨域JSONP请求?我想使用JavaScript本身,然后解析数据并使其成为对象,这样我就可以使用它了。我必须使用外部库吗?如果没有,我该怎么做呢?
发布于 2011-05-26 09:38:01
function foo(data)
{
// do stuff with JSON
}
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
发布于 2012-10-24 16:19:14
轻量级示例(支持onSuccess和onTimeout)。如果需要,需要在URL中传入回调名称。
var $jsonp = (function(){
var that = {};
that.send = function(src, options) {
var callback_name = options.callbackName || 'callback',
on_success = options.onSuccess || function(){},
on_timeout = options.onTimeout || function(){},
timeout = options.timeout || 10; // sec
var timeout_trigger = window.setTimeout(function(){
window[callback_name] = function(){};
on_timeout();
}, timeout * 1000);
window[callback_name] = function(data){
window.clearTimeout(timeout_trigger);
on_success(data);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
return that;
})();
示例用法:
$jsonp.send('some_url?callback=handleStuff', {
callbackName: 'handleStuff',
onSuccess: function(json){
console.log('success!', json);
},
onTimeout: function(){
console.log('timeout!');
},
timeout: 5
});
在GitHub:https://github.com/sobstel/jsonp.js/blob/master/jsonp.js
发布于 2011-05-26 09:37:05
我的理解是你实际上在JSONP中使用脚本标记,所以...
第一步是创建处理JSON的函数:
function hooray(json) {
// dealin wit teh jsonz
}
确保在全局级别上可以访问此函数。
接下来,向DOM中添加一个脚本元素:
var script = document.createElement('script');
script.src = 'http://domain.com/?function=hooray';
document.body.appendChild(script);
该脚本将加载API提供程序构建的JavaScript,并执行它。
https://stackoverflow.com/questions/6132796
复制相似问题