[英]Returning json in asp.net webservice
在我的應用程序中,我們在頁面中使用prototype1.4.2。
我們需要支持延遲加載的樹視圖(發出 ajax 請求並將來自服務器的數據添加到節點),然后我找到了
它是基於原型構建的。
還有一個function:
onopenpopulate:
它將根據用戶提供的“openlink”從服務器加載數據。
在分支打開后調用。 當它打開時,它會在頁面 openlink 上發起一個 Ajax 請求,並將 Ajax 響應發送給用戶 function。 它必須返回一個 JSON 字符串,表示一個或多個 TafelTreeBranch 的數組。 覆蓋 TafelTree 的 setOnOpenPopulate()
但它需要服務器返回純 json 數據格式。
我以這種方式創建了一個網絡服務:
[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string loadData(id) {
//some logic according the id
return "{id:0,name:'xx'}";
}
}
但是,當我調用此服務時,請使用:
http://xxx/UtilService/loadData?id=0
我總是得到 xml 格式。
通過谷歌,似乎我在發出 ajax 請求時必須設置“內容類型”。
但是,在我的情況下,ajax 是由“TafelTree”發送的,我無法添加額外的參數。
任何想法? 還是使用另一個基於原型的樹?
您可以使用 jquery 進行 Ajax 調用。
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "webServiceUrl/MethodName",
data: "{Id: '" + id + "'}",
dataType: "json",
success: loadSucceeded,
error: loadFailed,
async: true
});
function loadSucceeded(result, status)
{
var data = result.d;
}
function loadFailed(result, status)
{
}
注意不一定要返回字符串,可以返回object的列表。
[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService
{
[WebMethod]
public List<string> loadData(id) {
//some logic according the id
return new List<string>(){"data"};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.