我正在使用 .NET 2.0 和 Visual Studio 2005 尝试创建一个可以同时作为 SOAP/XML 和 JSON 使用的 Web 服务。我读了Dave Ward's Answer问题How to return JSON from a 2.0 asmx web service (除了在 Encosia.com 阅读其他文章),但我无法弄清楚我需要如何设置我的 asmx 文件的代码才能使用 jQuery 处理 JSON。
两个问题:
- 如何在我的 .NET 2.0 ASMX 文件中启用 JSON?
- 可以使用 JSON 使用服务的简单 jQuery 调用是什么?
此外,我注意到由于我使用的是 .NET 2.0,所以我无法实现 using System.Web.Script.Services.ScriptService。
这是我的演示 ASMX 服务的 C# 代码:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
/// <summary>
/// Summary description for StockQuote
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class StockQuote : System.Web.Services.WebService {
public StockQuote () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public decimal GetStockQuote(string ticker)
{
//perform database lookup here
return 8;
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
这是我在互联网上找到并尝试修改的 jQuery 片段:
$(document).ready(function(){
$("#btnSubmit").click(function(event){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://bmccorm-xp/WebServices/HelloWorld.asmx",
data: "",
dataType: "json"
})
event.preventDefault();
});
});
请您参考如下方法:
您可以在 .NET 2.0/Visual Studio 2005 中使用 ScriptService。您只需要安装 ASP.NET AJAX Extensions在 .NET 3.5 之前发布,在它成为框架的核心组件之前。
