gpt4 book ai didi

web-services - ajax调用失败时在vb.net中获取xhr对象

转载 作者:行者123 更新时间:2023-12-03 08:02:23 26 4
gpt4 key购买 nike

我在jQuery.ajax通话中遇到大问题。每当单击更新按钮时,我都会调用Web服务。我有一个单独的Web服务类,其中包含几种方法。当我调用Web服务方法时,我已经进行了错误处理,并将错误信息记录在db中,之后我必须将XMLHttpRequest覆盖意味着错误对象的“ex”。是否可以将SqlException分配给xhr中的ajax对象(VB.NET)?请帮助我,它对我更有用。

最佳答案

对的,这是可能的!我尝试在VB.NET中对其进行描述(大多数情况下,我使用C#,但希望不会出现语法错误)。让我们拥有Web服务

<WebMethod()> _
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function GetData(ByVal Age As Integer) As String
If Age <= 0 Then
Throw(New ArgumentException("The parameter age must be positive."))
End If
'... some code
End Function

C#中的相同代码如下所示
[WebMethod]
[ScriptMethod (UseHttpGet=true)]
public string GetData(int age)
{
if (age <= 0)
throw new ArgumentException("The parameter age must be positive.");
// some code
}

在年龄输入为负的情况下,将抛出 ArgumentException异常(对于所有类似 SqlException的异常,我解释的所有内容均保持不变)。

现在,您有了一个使用 jQuery.ajax调用服务的JavaScript代码。然后,您可以通过以下方式扩展代码以支持异常处理:
$.ajax({
type: "GET",
url: "MyWebService.asmx/GetData",
data: {age: -5},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, xhr) {
// use the data
},
error: function(xhr, textStatus, ex) {
var response = xhr.responseText;
if (response.length > 11 && response.substr(0, 11) === '{"Message":' &&
response.charAt(response.length-1) === '}') {

var exInfo = JSON.parse(response);
var text = "Message=" + exInfo.Message + "\r\n" +
"Exception: " + exInfo.ExceptionType;
// + exInfo.StackTrace;
alert(text);
} else {
alert("error");
}
}
});

如果引发异常,我们将以JSON格式接收有关错误的信息。我们将其反序列化为具有 MessageExceptionTypeStackTrace属性的对象,然后显示如下错误消息
Message: The parameter age must be positive.
Exception: System.ArgumentException

在实际的应用程序中,您可能永远不会显示 StackTrace属性的值。最重要的信息在 Message中:异常文本;在 ExceptionType中:异常名称(例如 System.ArgumentExceptionSystem.Data.SqlClient.SqlException)。

关于web-services - ajax调用失败时在vb.net中获取xhr对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3635133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com