问题描述
我开始学习ajax.而且我有API.API返回两种类型的响应1.当我有数据并且系统中没有数据时成功2.服务器出错时发生错误(异常).
I started learning ajax. And I have API. API return two types of response1. Succes when I have data and when there's no data in system2. Error (exception) when there's server error.
在API文档中,我有类似的内容
In API documentation I have something like this
字段-成功类型-布尔值响应状态-正确/错误
field - successtype - booleanresponse status - true/false
字段-数据类型-对象
内部数据对象中还有其他字段.我想做的很简单.在系统中时显示数据,在没有数据时显示错误消息.
Inside data object I have other fields. What I want to do is simple. Show data when it is in system and show error mesage when there's no data.
根据文档,这是系统中有数据时的示例正确响应
According to documentation this is sample correct response when data is in the system
{
"success": true,
"data": {
"office_id": 1,
"office_type": "s",
"registrar_name": null,
"registrar_mobile": null,
"registrar_email": null
}
}
并在系统中没有数据时纠正响应
and correct response when there's no data in the system
{"success": true}
或
{
"success": true,
"err": "error message"
}
这就是我现在所得到的.当它在系统中找到mydata时,它将正确显示字段.但是,当系统中没有数据时,我将无法定义.这段代码有什么问题?
This is what I got at this moment. When it found mydata in system it shows field properly. But when there's no data in system I got undefined. What's wrong with this code?
$('#test').on('click', function(){
$.ajax({
dataType: 'json',
type:"GET",
url:"http://mywebsite.com/api/mydata",
success: function(response, data) {
console.log(data.data);
},
err: function(response, data) {
console.log("no data");
}
});
});
推荐答案
首先根据文档第二个参数(在本例中为 data
)将是 textStatus .
First of all change your success function to only have one parameter as according to the documentation the second parameter (named data
in this case) will be the textStatus.
然后您可以仅检查响应的属性以了解是否有数据或响应是否有错误
And then you can just check the properties of the response to find out if you have data or if the response has an error
success: function (response) {
if (response.err != undefined) {
console.log("Error");
}
if (response.data != undefined) {
console.log("There is data");
} else {
console.log("No data")
}
}
请注意您的示例数据中带有错误的响应仍然具有 success:true
,在我看来,这有点愚蠢,因为如果有错误,它就不会成功.
Please note in your example data the response with an error still has success:true
, this to me seems a bit silly as it shouldn't be successful if there is an error.
这篇关于当没有数据与jQuery Ajax获取时显示错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!