当没有数据与jQuery Ajax获取时显示错误消息

编程入门 行业动态 更新时间:2024-10-28 16:30:39
本文介绍了当没有数据与jQuery Ajax获取时显示错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我开始学习ajax.而且我有API.API返回两种类型的响应1.当我有数据并且系统中没有数据时成功2.服务器出错时发生错误(异常).

I started learning ajax. And I have API. API return two types of response 1. Succes when I have data and when there's no data in system 2. Error (exception) when there's server error.

在API文档中,我有类似的内容

In API documentation I have something like this

字段-成功类型-布尔值响应状态-正确/错误

field - success type - boolean response 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:"mywebsite/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获取时显示错误消息

本文发布于:2023-10-30 22:14:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544152.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   消息   数据   Ajax   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!