ASP.NET Web服务返回xml而不是json

时间:2012-02-04 03:09:24

标签: jquery asp.net ajax json web-services

这是我的代码;

$(document).ready(function () {
    $('#btnAddCat').click(function () {
        var cn = $('#txtCategoryName').val();
        alert(cn);
        $.ajax({
            type: 'Post',
            url: "../_ws/news.asmx/InsertCategory",
            data: { catName: + cn  },
            contenttype: 'application/json; charset=utf-8',
            datatype: 'json',
            async: false,
            success: function (msg) {
                alert(msg);
            },
            error: function (msg) {
                alert('failure');
                alert(msg);
            }
        });
    });
});

这是news.asmx web服务中的代码

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
'<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class News
    Inherits System.Web.Services.WebService


    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
    Public Function InsertCategory(ByVal catName As String) As String
        Dim newid = KTOEOS.NewsCategories.InsertCategory(catName)
        Return "{'c':" & newid & "}".ToString
    End Function

End Class

返回的结果是:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{'c':21}</string>

如果我将jQuery部分更改为read;

...

data: { catName: + cn  },

...

然后我收到一个错误:

System.InvalidOperationException: Missing parameter: catName

我做错了什么?

2 个答案:

答案 0 :(得分:0)

可能是因为你习惯了VB不区分大小写。

尝试这些行(注意国会大厦T):

 contentType: 'application/json; charset=utf-8',
 dataType: 'json',

答案 1 :(得分:0)

从您的网络服务代码中取消注释以下行。

<System.Web.Script.Services.ScriptService()>

为什么要将async设为false?这将完全停止浏览器,直到服务器响应。