我有一张表格来收集有关产品的信息(即来自亚马逊)。我试图在URL输入模糊时触发YQL ajax请求。目前,控制台没有错误,但也没有结果。这是我的表单输入:
<div class="uk-form-row">
<div class="uk-form-label"><?php echo $this->form->getLabel('item_url'); ?></div>
<div class="uk-form-controls "><input type="text" name="jform[item_url]" id="jform[item_url]" value="<?php if (!empty($this->item->id)) { echo $this->item->item_url;}; ?>" class="uk-form-large uk-width-medium-1-1" placeholder="http://" aria-required="required" required="required"/></div>
</div>
<script type="text/javascript">
jQuery( "#jform[item_url]" ).blur(function() {
var path = jQuery('#jform[item_url]').val();
requestCrossDomain(path, function(results) {
jQuery('#url_results').html(results);
});
});
</script>
<div id="url_results">
</div>
我的功能:
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no url was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
jQuery.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
答案 0 :(得分:0)
此问题与您的服务器有关。您只需在服务器上设置Access-Control-Allow-Origin
标头即可。查找您的服务器语言,了解如何设置Access-Control-Allow-Origin
将其设置为*将接受来自任何域的跨域AJAX请求。 另一种方法是使用'JSONP'数据类型返回数据。
<强>参考强>