asmx Web 服务、json、javascript/jquery?
我正在使用 asmx 从数据库检索一些数据,
public class TestPage1
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
[WebMethod]
public EntityLayer.TestPage1 GetData(int id)
{
TestPage1 test = TestPage1.GetData(id).SingleOrDefault();
return test;
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/GetData",
data: "{id}",
dataType: "json"
});
如何在 javascript 中反序列化测试对象? 还有更好的方法吗? 谢谢
I am using asmx to retrieve some data from DB,
public class TestPage1
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
[WebMethod]
public EntityLayer.TestPage1 GetData(int id)
{
TestPage1 test = TestPage1.GetData(id).SingleOrDefault();
return test;
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/GetData",
data: "{id}",
dataType: "json"
});
How Do I desrialize test object in javascript??
and is there a better way?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您查看我之前的回答来了解关闭问题如何构建 JSON 对象以发送到 AJAX WebService? 和 如果 ContentType 不是 JSON,我可以从 .asmx Web 服务返回 JSON 吗?
正确的代码应如下所示
,
其中
JSON.stringify
是脚本 json2.js 中的函数,您可以从 http://www.json.org/js.html。如果
id
值是整数JSON.stringify(myData)
与myData
相同,但对于所有更复杂的示例,我强烈建议您使用此功能。从代码中您还可以看到,Web 方法的所有结果都将保存在属性
d
中,因此您应该使用例如response.d.FirstName
语法来访问名字。更新:如果是 HTTP GET,
data
参数应为{id:JSON.stringify(myData)}
。对于 HTTP POST:JSON.stringify({id:myData})
I recommend you look my previous answer for the close questions How do I build a JSON object to send to an AJAX WebService? and Can I return JSON from an .asmx Web Service if the ContentType is not JSON?
The correct code should looks like following
and
where
JSON.stringify
is a function from the script json2.js which you can download from http://www.json.org/js.html.If the
id
values are integerJSON.stringify(myData)
are the same asmyData
, but for all more complex examples I strictly recommend you to use this function.How you can also see from the code the all results of the web method will be saved in the property
d
, so you should use for exampleresponse.d.FirstName
syntax to access the first name.UPDATED: In case of HTTP GET the
data
parameter should be{id:JSON.stringify(myData)}
. In case of HTTP POST:JSON.stringify({id:myData})
有几件事...
一些未经测试的示例代码:
A couple things...
Some untested sample code: