"No Transport"错误是jQuery在进行跨域AJAX请求时可能遇到的常见错误,表明浏览器无法找到合适的传输方式来完成请求。这通常发生在跨域请求或使用特殊协议(如file://)时。
在WebService端添加CORS头:
// ASP.NET Web API示例
public static void Register(HttpConfiguration config)
{
// 允许所有来源(生产环境应限制为特定域名)
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
}
$.ajax({
url: 'http://example.com/webservice',
dataType: 'jsonp',
jsonp: 'callback',
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error(error);
}
});
对于本地文件开发环境,可以添加以下代码:
// 允许jQuery在file://协议下工作
if (window.location.protocol === 'file:') {
$.support.cors = true;
}
// 前端请求同域下的代理接口
$.ajax({
url: '/api/proxy?url=' + encodeURIComponent('http://example.com/webservice'),
type: 'GET',
success: function(data) {
console.log(data);
}
});
// 确保页面协议与服务协议一致
var serviceUrl = window.location.protocol + '//example.com/webservice';
$.ajax({
url: serviceUrl,
// ...
});
$(document).ready(function() {
// 检查是否在本地文件环境
if (window.location.protocol === 'file:') {
$.support.cors = true;
}
// 调用WebService
$.ajax({
url: 'https://example.com/api/service',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ param1: 'value1' }),
dataType: 'json',
crossDomain: true,
success: function(response) {
console.log('Success:', response);
},
error: function(xhr, status, error) {
console.error('Error:', status, error);
}
});
});
通过以上方法,您应该能够解决jQuery调用WebService时遇到的"No Transport"错误问题。
没有搜到相关的文章