使用JSONP错误jQuery的Ajax请求 [英] jQuery ajax request using jsonp error
问题描述
我正在写一个应用程序,我需要从其他服务器访问一些JSON数据在客户端。由于跨域问题我打算使用JSONP。 jQuery的可以让我这个用$ .getJSON()方法来做,但是,我没有办法告诉如果该方法失败(即服务器没有响应或东西)。所以我想尽了办法来获得使用$阿贾克斯,而不是JSON数据。但它不工作,我不知道什么尝试。 下面一个例子,显示我的问题:
I'm writing an app and I need to access some json data in the client side from another server. Because of the cross domain issue I plan on using jsonp. jQuery allows me to do this using the $.getJSON() method, however, I have no way to tell if the method has failed (i.e., the server is not responding or something). So I tried the approach to get the JSON data using $.ajax instead. But it's not working and I don't know what to try. Here an example showing my issue:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>TEST</title>
<script type="text/javascript" src="scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#button_detect').click(function(){
var feedApiAjax = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=';
var feedApiGetJSON = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=';
var feedUrl = 'http://www.engadget.com/rss.xml';
$.ajax({
url: feedApiAjax + feedUrl,
datatype: 'jsonp',
success: function(data) {
console.log('$.ajax() success');
},
error: function(xhr, testStatus, error) {
console.log('$.ajax() error');
}
});
$.getJSON(
feedApiGetJSON + feedUrl,
function(data) {
console.log('$.getJSON success');
});
});
});
</script>
</head>
<body>
<div id="button_detect">CLICK ME!!!!</div>
</body>
如果您创建了这个code一个网页,点击点击我分区,你会看到$ .getJSON请求工作和$就一个没有了。我试图把/删除回调=? TG,用JSONP和JSON数据类型,但非这个工作。
If you create a web page with this code and click on the "Click Me" div you'll see that the $.getJSON request is working and the $.Ajax one is not. I've tried putting/removing the "callback=?" tg, used "jsonp" and "json" data types, but non of this worked.
这是什么可能我做任何想法错了?
Any idea on what might I be doing wrong?
干杯!
推荐答案
我以前也遇到过这样的错误,并且使用的的jQuery JSONP
I encountered this error before, and solved after using jquery-JSONP
[示例]
$.getJSON('http://server-url/Handler.ashx/?Callback=DocumentReadStatus',
{
userID: vuserID,
documentID: vdocumentID
},
function(result) {
if (result.readStatus == '1') {
alert("ACCEPTED");
}
else if (result.readStatus == '0') {
alert("NOT ACCEPTED");
}
else {
alert(result.readStatus);
}
});
这篇关于使用JSONP错误jQuery的Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!