asp.net - 无法使用 jQuery 从 ASP.NET Web 服务返回 JSON 对象

标签 asp.net web-services json jquery

对于这个看似常见的问题,我找到了许多“解决方案”,但可惜的是,似乎没有一个对我有用 - 当然。我有一些 jQuery 代码试图发布到 ASP.NET 3.5 Web 服务。 Web 服务应该返回一些 json。我收到 501 Internal Server 错误,代码如下,但根据网上找到的解决方案,这应该是这样的! jquery 代码中的错误函数显示解析器错误。如果我更改数据参数传递到服务的方式 ("userID=3456"),并删除 contentType 属性并将 dataType 更改为“text”,则不会出现错误,但会返回 JSON在 XML 字符串中。

这是我的 jQuery 代码:

$.ajax({
        type: "POST",
        url: "mywebservice.asmx/Initialize",
        data: "{'userID': '3456'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            alert("success");
        },
        error: function(request, status, errorThrown) {
            alert(status);
            alert(errorThrown);
        }
});

这是我的 ASP.NET 代码:

<WebMethod()> _
Public Function Initialize(ByVal userID As Integer) As String
    Dim scormInstance As New CMI(userID)
    Return scormInstance.ToJsonString
End Function

以下是通过我的浏览器 (Firefox 3.5.1) 的 HTTP 请求和响应

http://localhost/cognition/webservices/cognitionapi.asmx/Initialize

POST /cognition/webservices/cognitionapi.asmx/Initialize HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1 (.NET CLR 3.5.30729)
Accept: application/json, text/javascript, */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost/cognition/scorm-test2.html
Content-Length: 20
Cookie: RadEditorGlobalSerializeCookie=[_ctl0__ctl0__ctl0_Content_mainContent_mainContent_txtSpecialInstructionsModules]-[]#[_ctl0__ctl0__ctl0_Content_mainContent_mainContent_txtSpecialInstructionsToolbars]-[]#
Pragma: no-cache
Cache-Control: no-cache
{"userID":"1234"}

HTTP/1.x 500 Internal Server Error
Cache-Control: private
Content-Length: 4956
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Mon, 27 Jul 2009 21:24:41 GMT

关于我到底做错了什么有什么想法吗???!!!!!!???

谢谢!

最佳答案

查看了一些正在运行的代码后,我在函数上发现了这个装饰:

[WebMethod(), ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]

我传入的postdata也是Json格式,即:

var postdata = "{'variable':'value'}";

关于asp.net - 无法使用 jQuery 从 ASP.NET Web 服务返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1190716/

相关文章:

java - 通过java程序从WSDL生成java类

javascript - 来自 2 个 MySQL 查询的数组用于使用 javascript 的 2 个选择

javascript - 将 JSON 字符串传递给 PHP 并推送到数组

javascript - 日历 iframe 第一次显示在文本框的右侧,然后从那时起显示在文本框的下方

c# - Excel 导入的 SQL 注入(inject)漏洞

java - 内存数据库选项(开源和基于 Java)

c# - 如何构建base64 rest web服务来上传带有其他信息的图像文件

javascript - 无法从 json 对象获取数据

c# - 带按钮的用户控件 - 当 uc 动态添加到另一个页面时

asp.net - URL 重写从/default.aspx 到/