您的主要问题似乎是您在 HTTP 标头中返回 JSON 数据,而不是作为响应的内容。你可能想做这样的事情:
Response.ContentType = "application/json";
Response.Write(result);
Response.End();
这可能会解决您的直接问题,但我强烈建议您避免使用 ASPX 页面的直接输出的方法。当您真正想要的是一个简单的 JSON 端点时,到达 Page_Load 点会涉及很多不必要的开销。更何况,不需要手动处理 JSON 序列化。
如果您从服务器端的对象构建 JSON 字符串,则可以使用 ASP.NET AJAX“页面方法”直接返回该字符串并让框架处理序列化。像这样:
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() 调用中指定几个额外的参数:
$.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/