$ .ajax - 发送数据属性的对象

时间:2011-12-27 15:35:42

标签: javascript jquery asmx

我正在尝试使用jQuery调用asmx Web服务方法,并为data传递一个实际的JavaScript对象,并返回JSON。我能来的最接近的是:

$.ajax({
     url: "WebService.asmx/HelloWorld",
     type: "POST",
     contentType: "application/json; charset=utf-8",
     data: JSON.stringify({ num: 12, name: "Adam" }),
     dataType: "json",
     success: function (data) { alert(data.d); }
 });

如何在没有首次字符串化我的对象的情况下成功拨打此电话

我尝试了这个(删除了contentType)

$.ajax({
    url: "WebService.asmx/HelloWorld",
    type: "POST",
    data: { num: 12, name: "Adam" },
    dataType: "json",
    success: function (data) { alert(data.d); }
});

但是这会以XML格式返回结果,而不是json。

这是网络方法:

[WebMethod]
[ScriptMethod]
public string HelloWorld(int num, string name) {
    return ++num + name;
}

修改

以下是请求标头的屏幕截图。显然,内容类型设置为xml以进行响应。

enter image description here

1 个答案:

答案 0 :(得分:2)

<德尔> 设置ResponseFormat:     [的WebMethod]     [ScriptMethod(ResponseFormat = ResponseFormat.Json)]     public string HelloWorld(int num,string name){         return ++ num + name;     } 只需注意:asmx不会为GET仅返回JSON POST

<小时/> Per Dave的评论

  

使用ASMX和ASPX JSON端点是不可能的。它们需要application / json Content-Type和POST请求或没有JSON。