AJAX内容类型问题

时间:2015-03-16 09:32:18

标签: jquery ajax

为什么这个ajax调用不起作用?当我将其更改为contentType: "application/json; charset=utf-8"时,其间有分号? 源代码可以通过以下网址进行测试。试着测试一下。 https://jsfiddle.net/rrcjdv6e/7/

$.ajax({
    type: "POST",
    url: "WebService/HelloWorldWebService.asmx/Test",
    data: {},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        $("#divResponse").show("slow");
        $("#divResponse").css("background-color", "green");
        $("#divResponse").css("color", "white");
        $("#divResponse").css("text-align", "center");
        $("#divResponse").css("margin", "20px");
        $("#divResponse").text(response.d);
    },
    failure: function (response) {
        alert(response.d);
    }
});
[WebMethod]
public string Test()
{
    return "Hello World " ;
}

2 个答案:

答案 0 :(得分:0)

在WebMethod中,您需要返回json数据,或者将dataType更改为text

答案 1 :(得分:0)

只需从Ajax调用中删除contentTypedataType属性即可。默认情况下,内容类型应为application/x-www-form-urlencoded

$.ajax({
    type: "POST",
    url: "WebService/HelloWorldWebService.asmx/Test",
    data: {},
    success: function (response) {
        $("#divResponse").show("slow");
        $("#divResponse").css({
            "background-color": "green",
            "color": "white",
            "text-align": "center",
            "margin": "20px"
        });
        $("#divResponse").text(response);
    },
    failure: function (response) {
        alert(response);
    }
});