jQuery 如何让 JQGrid 识别服务器发送的错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1636580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get JQGrid to recognize server sent Errors?
提问by ZeroCool
I have a jqgrid that's functionning very well.
我有一个运行良好的 jqgrid。
I was wondering is it possible to catch server sent errors ? how Is it done ?
我想知道是否有可能捕获服务器发送的错误?怎么做的?
采纳答案by Samuel Meacham
I have recently made extensive use of jqgrid for a prototype project I am working on for CB Richard Ellis (my employer). There are many way to populate a jqgrid, as noted in the documentation: (see the "retrieving data" node).
我最近在为 CB Richard Ellis(我的雇主)工作的原型项目中广泛使用了 jqgrid。有很多方法可以填充 jqgrid,如文档中所述:(请参阅“检索数据”节点)。
Currently I make a service call that returns a json string that when evaluated, gives me an object that contains the following:
目前,我进行了一个服务调用,该调用返回一个 json 字符串,该字符串在评估时为我提供一个包含以下内容的对象:
- ColumnNames: string[]
- ColumnModels: object[] (each object has the properties "name", "index" and "sortable")
- Data: object[] (each object has properties that match the names in the column model)
- TotalRows: int
- 列名:字符串[]
- ColumnModels: object[](每个对象都有属性“name”、“index”和“sortable”)
- 数据:object[](每个对象都有与列模型中的名称匹配的属性)
- 总行数:int
In my success callback, I manually create the jqgrid like this: ("data" is the object I get when evaluating the returned json string).
在我的成功回调中,我像这样手动创建 jqgrid:(“数据”是我在评估返回的 json 字符串时得到的对象)。
var colNames = data.ColumnNames;
var colModel = data.ColumnModels;
var previewData = data.PreviewData;
var totalRows = data.TotalRows;
var sTargetDiv = userContext[0]; // the target div where I'll create my jqgrid
$("#" + sTargetDiv).html("<table cellpadding='0' cellspacing='0'></table>");
var table = $("#" + sTargetDiv + " > table");
table.jqGrid({
datatype: 'local',
colNames: colNames,
colModel: colModel,
caption: 'Data Preview',
height: '100%',
width: 850,
shrinkToFit: false
});
for (var row = 0; row < previewData.length; ++row)
table.addRowData(row, previewData[row]);
So you can see I manually populate the data. There is more than 1 kind of server error. There is the logical error, which you could return as a property in your json string, and check before you try to create a jqgrid (or on a per-row basis).
所以你可以看到我手动填充数据。存在超过 1 种服务器错误。存在逻辑错误,您可以将其作为 json 字符串中的属性返回,并在尝试创建 jqgrid(或基于每行)之前进行检查。
if (data.HasError) ...
Or on a per-row basis
或者在每行的基础上
for (var row = 0; row < previewData.length; ++row)
{
if (previewData[row].HasError)
// Handle error, display error in row, etc
...
else
table.addRowData(row, previewData[row]);
}
If your error is an unhandled exception on the server, then you'll probably want an error callback on your async call. In this case, your success callback that (presumably) is creating your jqgrid won't be called at all.
如果您的错误是服务器上未处理的异常,那么您可能需要在异步调用中进行错误回调。在这种情况下,根本不会调用(大概)正在创建 jqgrid 的成功回调。
This, of course, applies to manually populating a jqgrid, which is only one of the many options available. If you have the jqgrid wired directly to a service call or a function to retrieve the data, then that's something else entirely.
当然,这适用于手动填充 jqgrid,这只是众多可用选项之一。如果您将 jqgrid 直接连接到服务调用或检索数据的函数,那么这完全是另一回事。
On the documentation page, look under Basic Grids > Events. There you'll see the "loadError" event that might come in handy.
在文档页面上,查看基本网格 > 事件。在那里你会看到可能会派上用场的“loadError”事件。
回答by r00fus
If you look at the jqgrid demo siteand look at "What's new in version 3.2" There should be a section about controlling server errors.
如果您查看jqgrid 演示站点并查看“3.2 版中的新功能”,那么应该有一个关于控制服务器错误的部分。
Specifically, it uses a callback parameter loadError:
具体来说,它使用了一个回调参数 loadError:
loadError : function(xhr,st,err) {
jQuery("#rsperror").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText);
}
As mcv states above, some errors are data errors, so you'll need to handle those specifically.
正如上面 mcv 所述,有些错误是数据错误,因此您需要专门处理这些错误。
回答by mcv
Use the callbacks. If you get an actual http error (a 400 or 500, for example), loadError(xhr, status, error) is triggered.
使用回调。如果您收到实际的 http 错误(例如 400 或 500),则会触发 loadError(xhr, status, error)。
But some errors (like validation) shouldn't throw a 400 or 500 error. But you can still catch those in loadComplete(xhr). Parse your json, and check for whatever way you're using to identify errors. For example, I'm doing this in my loadComplete():
但是某些错误(如验证)不应引发 400 或 500 错误。但是您仍然可以在 loadComplete(xhr) 中捕获它们。解析您的 json,并检查您使用的任何方式来识别错误。例如,我在 loadComplete() 中这样做:
if (jsonResponse.errors) {
$.each(jsonResponse.errors, function(i, val){
addErrorMessage($("#"+val.field), val.message);
});
}
if (jsonResponse.errors) {
$.each(jsonResponse.errors, function(i, val){
addErrorMessage($("#"+val.field), val.message);
});
}
回答by Don
You can use the loadError
event in jqGrid definition (see documentation). E.g.:
您可以loadError
在 jqGrid 定义中使用该事件(请参阅文档)。例如:
//Catch errors
loadError = function(xhr, textStatus, errorThrown) {
var error_msg = xhr.responseText
var msg = "Some errors occurred during processing:"
msg += '\n\n' + error_msg
alert(msg)
}
回答by Nutshell
Another thing to remember/ or that I found is that if you are using Asp.net you need to turn
要记住/或我发现的另一件事是,如果您使用的是 Asp.net,则需要转
in the section - this will allow you to introspect the Message coming back as well.
在 部分 - 这将允许您内省返回的消息。
回答by Matt
If you're using jqGrid with the options
如果您使用带有选项的 jqGrid
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
datatype: "json",
url: wsPath
to load data via AJAX and web services or MVC controllers, then this answer is for you.
要通过 AJAX 和 Web 服务或 MVC 控制器加载数据,那么这个答案适合您。
Notethat if a runtime error occurs in the web method dealing with the AJAX call, it can't be catched via loadError, because loadError only catches HTTP related errors. You should rather catch the error in the web methodvia try ... catch
, then pass it in JSON format in the catch block using return JsonString
. Then it can be handled in the loadComplete event:
注意,如果在处理 AJAX 调用的 web 方法中出现运行时错误,则无法通过 loadError 捕获,因为 loadError 仅捕获与 HTTP 相关的错误。你还是捕获错误的Web方法通过try ... catch
,然后用它传递以JSON格式在catch块return JsonString
。然后就可以在loadComplete事件中处理了:
loadComplete: function (data) {
if (this.p.datatype === 'json') {
if (data!==undefined && data!==null && isErrorJson(data)) {
ShowErrorDialog(getJsonError(data));
}
// ...
}
The functions above have the following meaning, implement them as needed:
以上函数含义如下,根据需要实现:
isErrorJson(data)
: returns true, if the data object contains error as defined in your web methodgetJsonError(data)
: returns the string with the error message as defined in your web methodShowErrorDialog(msg)
: displays the error message on screen, e.g. via jQueryUI dialog.
isErrorJson(data)
: 如果数据对象包含您的网络方法中定义的错误,则返回 truegetJsonError(data)
: 返回带有 Web 方法中定义的错误消息的字符串ShowErrorDialog(msg)
: 在屏幕上显示错误消息,例如通过 jQueryUI 对话框。
In the web service method you can use JavaScriptSerializer
to create such an error object, for the 2 JavaScript methods above you can use the jQuery function $.parseJSON(data.d)
to get the message out of the JSON object.
在 Web 服务方法中,您可以使用JavaScriptSerializer
创建此类错误对象,对于上述 2 个 JavaScript 方法,您可以使用 jQuery 函数$.parseJSON(data.d)
从 JSON 对象中获取消息。
回答by SeanJA
From what I see, it returns the data as a json string. So what you have to do is add an error handler that formats the error as a json string and prints it out as one. This can be done in php with the
据我所知,它以 json 字符串形式返回数据。因此,您需要做的是添加一个错误处理程序,将错误格式化为 json 字符串并将其打印为一个字符串。这可以在 php 中使用
set_error_handler
function.
功能。
The error handler would then I guess push the data in to jsonReturn.error, so you would just need to check for that when you are adding your data to the table.
然后我猜错误处理程序会将数据推送到 jsonReturn.error,因此您只需要在将数据添加到表中时检查它。
If you are throwing exceptions instead of letting it get all the way to errors (probably a better practice), then you would want to format the exception as a json string.
如果您要抛出异常而不是让它一直出错(可能是更好的做法),那么您可能希望将异常格式化为 json 字符串。
Since it is returning the data in an xml format, you would want to parse the xml:
由于它以 xml 格式返回数据,因此您需要解析 xml:
<xml>
<error>
error message
</error>
</xml>
like this:
像这样:
$(request.responseXML).find("error").each(function() {
var error = $(this);
//do something with the error
});
Shamelessly borrowed from: http://marcgrabanski.com/article/jquery-makes-parsing-xml-easy
无耻地借用:http: //marcgrabanski.com/article/jquery-makes-parsing-xml-easy
回答by ZeroCool
function gridCroak(postdata, _url, grid, viewCallBack, debug) {
$(".loading").css("display", "block");
$.ajax({
type: 'POST',
url: _url,
data: postdata,
dataType: "xml",
complete: function(xmldata, stat){
if(stat == "success") {
$(".loading").css("display", "none");
var errorTag = xmldata.responseXML.getElementsByTagName("error_")[0];
if (errorTag) {
$("#ErrorDlg").html(errorTag.firstChild.nodeValue);
$("#ErrorDlg").dialog('open');
} else {
var warningTag = xmldata.responseXML.getElementsByTagName("warning_")[0];
if (warningTag) {
$("#WarningDlg").html(warningTag.firstChild.nodeValue);
$("#WarningDlg").dialog('open');
} else {
if (debug == true) {
alert(xmldata.responseText);
}
jQuery(grid)[0].addXmlData(xmldata.responseXML);
if(viewCallBack) viewCallBack();
}
}
} else {
$("#ErrorDlg").html("Servizio Attualmente Non Disponibile !");
$("#ErrorDlg").dialog('open');
}
}
});
}
And In the Grid
在网格中
datatype : function(postdata) { gridCroak(postdata, 'cgi-bin/dummy.pl?query=stock',
"#list", null, false) },
At the end it does use the same approach I think.
最后它确实使用了我认为的相同方法。
Thanks all
谢谢大家