JQuery-Firefox中的$ .ajax ContentType问题 [英] JQuery - $.ajax ContentType Problem in Firefox
问题描述
我正在使用以下代码提出跨域JSON请求,
I am using following code to make a cross domain JSON request,
$.ajax({
type:"POST",
crossDomain:true,
contentType: "application/json; charset=utf-8",
data: {
domain: 'domain',
assettypes: 'Article',
sortby: 'mostreadcounter_total',
pagesize: '3',
format: 'json',
apikey: 'apiKey'
},
url: 'http://www.sample.com/search',
dataType: "json",
success: CallSucceed,
failure: CallFail,
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
}
});
但是我的电话失败了.在提琴手中,我看到内容类型为'text/html; charset = UTF-8",而我将contentType明确设置为"application/json; charset = UTF-8".
But my call is failing. In fiddler I see the the content type as 'text/html; charset=UTF-8' while I am explicitly setting contentType as 'application/json;charset=UTF-8.'
当我使用浏览器访问API时,它可以正常工作,并且Fiddler显示正确的内容类型.但是,一旦我使用JQuery发出请求,我的内容类型就会切换为text/html,并且我的请求将失败并出现405错误(不允许使用方法.)
When I access the API using browser, it works fine and Fiddler shows the proper content type. But as soon as I make the request using JQuery, my content type switches to text/html and my request fails with a 405 error (Method not allowed.)
这仅在Firefox 3.6中发生,而不是在IE中发生:(我尝试了两种Get/POSt方法,但我尝试在"BeforeSend"中添加和删除代码,但无济于事.
This is happening only in Firefox 3.6 and not in IE :( I ahve tried both Get/POSt methods, I have tried adding and removing the code in "BeforeSend" but to no avail.
有什么建议吗?
推荐答案
1.您不能使用post方法执行跨浏览器的ajax请求,而只能使用get
1. You cannot do a cross-browser ajax request with the post method, only with get
2.跨浏览器ajax请求可以使用JSONP
而不是JSON
来实现,是的,它们有所不同.
2. The cross-browser ajax request could be achieved with JSONP
not with JSON
, yes they are different somehow.
3.您需要能够在服务器端处理JSONP
请求.
3. You need to be able to handle JSONP
requests on your server side.
var data = {
domain: 'domain',
assettypes: 'Article',
sortby: 'mostreadcounter_total',
pagesize: '3',
format: 'json',
apikey: 'apiKey'
};
$.ajax({
url: 'http://www.sample.com/search?callback=?',
data: data,
success: CallSucceed,
failure: CallFail,
dataType: 'jsonp'
});
用于处理JSONP
请求的PHP示例代码
PHP sample code for handling a JSONP
request
$domain = $_GET['domain'];
$assettypes = $_GET['assettypes'];
// ... and so on
// you need the callback(success handler) name,
// so you can pass your JSON object to it
$callback = $_GET['callback'];
echo $callback.'('.json_encode(array('success' => true, /* and so on */)).')';
这篇关于JQuery-Firefox中的$ .ajax ContentType问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!