hol*_*ard 2 api ajax jquery get request
我已经创建了一个在json中返回数据的API,现在我正在创建一个应用程序,通过接收数据并在页面上使用它来测试API.但是,我的ajax代码(见下文)因某种原因失败,错误只是"错误"(错误:错误).
代码有什么问题?
代码:
$.ajaxSetup ({
url: "http://localhost:8000/products", // <--- returns json
type: "GET",
headers:{
"Accept":"application/json",
"Content-type":"application/x-www-form-urlencoded"
}
})
$.ajax({
success: function(data){
console.log("You made it!");
},
error: function(xhr) {
console.log("Error: " + xhr.statusText);
}
}).done(function(data){
console.log(data);
})
Run Code Online (Sandbox Code Playgroud)
这是我在Chrome(Inspector - > Network)中获得的信息:
名称:产品localhost /,方法: GET,状态:(已取消),类型:待定,发起人: jquery-latest.js:8434脚本,大小: 13B 0B,时间: 95ms 0.0天
我想我在这里知道你的问题.看起来你正在加载一个协议+域+端口(例如" http://localhost/")的页面,但随后调用AJAX请求到不同的协议,域或端口(在这种情况下可能只有端口不同:" http://localhost:8000/products").
这样您可能会遇到同源策略限制,这是浏览器的安全功能.在这种情况下,浏览器可能会指示特定请求已被"取消"(因为浏览器阻止了它).
您的问题有多种解决方案:
http://localhost/products"将http://localhost:8000/products在后台调用" "并返回其响应(作为SOP的一个转向),$.ajax({
/* ajax options omitted */
error: function (xmlHttpRequest, textStatus, errorThrown) {
if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)
return; // it's not really an error
else
// Do normal error handling
});
Run Code Online (Sandbox Code Playgroud)