如何使用VB.NET Web服务返回的对象

时间:2013-01-31 18:34:11

标签: ajax vb.net web-services

我有一个Javascript函数,它将字符串传递给VB.NET Web方法。这是Javascript

function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";

//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
 type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
    alert("It worked: " + e);
},
error: function (e) {
    alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial

这是VB.NET Web方法。 Web方法只需获取字符串并将其发送回Javascript:

   <WebMethod( )> _
Public Function testWebService(str As String) As String
    Return str
End Function

当Web方法成功返回时,我的AJAX块返回以下消息:

"It worked: [object Object]"

所以我的问题是,如何使用返回的对象?该对象应该是一个包含单词“hello world”的字符串,但是如何访问字符串值?

2 个答案:

答案 0 :(得分:1)

ASP.Net WebMethods将其返回值包装在具有d属性的JSON对象中。 (您可以在浏览器的开发人员工具的响应主体中看到这一点)

您需要编写e.d来获取实际值。

答案 1 :(得分:0)

如果你这样做:

$(e).text()

你会得到你的文字;

所以改为:

function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";

//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
 type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
    alert("It worked: " + $(e).text());
},
error: function (e) {
    alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial