简体   繁体   中英

ASP.NET web service returning xml instead of json

here is my code;

$(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);
            }
        });
    });
});

and here is the code in news.asmx web service

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

the returning result is:

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

If I change the jQuery part to read;

...

data: { catName: + cn  },

...

then I get an error:

System.InvalidOperationException: Missing parameter: catName

What am I doing wrong?

Probably it's because you are used to VB being case-insensitive.

Try these lines (note the capitol T):

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

Uncomment the below line form your web service code.

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

Why are you setting async to false ? This will stop the browser completely until server responds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM