asmx 网络服务、json、javascript/jquery? [英] asmx web service, json, javascript/jquery?
问题描述
我正在使用 asmx 从数据库中检索一些数据,
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"
});
如何在 javascript 中反序列化测试对象?有没有更好的方法?谢谢
How Do I desrialize test object in javascript?? and is there a better way? thanks
推荐答案
我建议您查看我之前的回答以解决问题如何构建要发送到 AJAX WebService 的 JSON 对象? 和 我可以返回吗如果 ContentType 不是 JSON,那么来自 .asmx Web 服务的 JSON?
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
[WebMethod]
[ScriptMethod (ResponseFormat = ResponseFormat.Json)]
public EntityLayer.TestPage1 GetData(int id)
{
TestPage1 test = TestPage1.GetData(id).SingleOrDefault();
return test;
}
和
var myData = 5;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/GetData",
//data: {id:JSON.stringify(myData)},
data: JSON.stringify({id:myData}),
dataType: "json",
success: function(response){
alert("UserName=" + response.d.UserName +
", FirstName=" + response.d.FirstName +
", MiddleName=" + response.d.MiddleName+
", LastName=" + response.d.LastName);
}
})
其中 JSON.stringify
是脚本 json2.js 中的一个函数,您可以从 http://www.json.org/js.html.
where JSON.stringify
is a function from the script json2.js which you can download from http://www.json.org/js.html.
如果 id
值是整数 JSON.stringify(myData)
与 myData
相同,但对于所有更复杂的例子,我严格推荐您使用此功能.
If the id
values are integer JSON.stringify(myData)
are the same as myData
, but for all more complex examples I strictly recommend you to use this function.
如何从代码中还可以看到web方法的所有结果都将保存在属性d
中,因此您应该使用例如response.d.FirstName
访问名字的语法.
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 example response.d.FirstName
syntax to access the first name.
UPDATED:在 HTTP GET 的情况下,data
参数应该是 {id:JSON.stringify(myData)}
.在 HTTP POST 的情况下:JSON.stringify({id:myData})
UPDATED: In case of HTTP GET the data
parameter should be {id:JSON.stringify(myData)}
. In case of HTTP POST: JSON.stringify({id:myData})
这篇关于asmx 网络服务、json、javascript/jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!