你的主要問題似乎是,你在HTTP頭而不是作爲響應的內容返回JSON數據。你可能想要做這樣的事情:
Response.ContentType = "application/json";
Response.Write(result);
Response.End();
這或許能夠立即解決的問題,但我會強烈建議您不要使用一個ASPX頁面的直接輸出中的方法。當你真正需要的只是一個簡單的JSON端點時,有很多不必要的開銷涉及到Page_Load的要點。更不用說,手動處理JSON序列化是沒有必要的。
如果您從服務器端的對象構建該JSON字符串,則可以使用ASP.NET AJAX「Page Method」直接返回該對象,並讓該框架處理序列化。像這樣:
public class PermissionsResult
{
public bool success;
public string message;
public int user_level;
public List<Switch> switches;
}
public class Switch
{
public int number;
public bool is_enabled;
public bool is_default;
}
// The combination of a WebMethod attribute and public-static declaration
// causes the framework to create a lightweight endpoint for this method that
// exists outside of the normal Page lifecycle for the ASPX page.
[WebMethod]
public static PermissionsResult GetPermissions(int UserLevel)
{
PermissionsResult result = new PermissionsResult();
// Your current business logic to populate this permissions data.
result = YourBusinessLogic.GetPermissionsByLevel(UserLevel);
// The framework will automatically JSON serialize this for you.
return result;
}
你必須將它適應到你自己的服務器端數據結構,但希望你明白了。如果您已經有了可以填充所需數據的現有類,則可以使用這些類而不是爲傳輸創建新類。
要call an ASP.NET AJAX Page Method with jQuery,你需要指定的$。阿賈克斯()調用了一對額外的參數:
$.ajax({
// These first two parameters are required by the framework.
type: 'POST',
contentType: 'application/json',
// This is less important. It tells jQuery how to interpret the
// response. Later versions of jQuery usually detect this anyway.
dataType: 'json',
url: 'MyPage.aspx/GetPermissions',
// The data parameter needs to be a JSON string. In older browsers,
// use json2.js to add JSON.stringify() to them.
data: JSON.stringify({ UserLevel: 1}),
// Alternatively, you could build the string by hand. It's messy and
// error-prone though:
data: "{'UserLevel':" + $('#UserLevel').val() + "}",
success: function(data) {
// The result comes back wrapped in a top-level .d object,
// for security reasons (see below for link).
$('#testp').append(data.d.message);
}
});
關於數據參數,這裏是它的信息需要是一個字符串:http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/
另外,這裏更多地介紹如何使用JSON.stringify()方法:http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/
.d問題最初可能會讓人困惑。基本上,JSON會回來這樣的,而不是你怎麼可能指望:
{"d": { "success": true, "message": "SUCCESS", "user_level": 25, "switches": [ { "number": 30, "is_enabled": false, "is_default": false }, { "number": 30, "is_enabled": false, "is_default": false } ]}}
這很容易解釋,一旦你指望它。當頂級容器是一個數組時,它通過減輕相當危險的客戶端漏洞使它更安全。不適用於此特定情況,但通常情況下不錯。你在這裏閱讀更多關於:http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
我明白它應該做什麼,但它不這樣做。問題是「成功:函數(數據){}」中的「數據」爲空。爲什麼它是空的? – 2010-08-24 21:27:49
如果「MyPage.aspx」是方法返回數據並說你的方法被稱爲「getData」的地方,那麼執行此操作: url:'MyPage.aspx/getData' – Silkster 2010-08-24 21:31:56
此外,參數應該與輸入值匹配爲該方法。如果沒有輸入變量,則使用 數據:「{}」 – Silkster 2010-08-24 21:33:05