gpt4 book ai didi

c# - 从 Javascript 调用 Web 服务时使用文档对象而不是 JSON

转载 作者:行者123 更新时间:2023-11-28 01:30:18 25 4
gpt4 key购买 nike

我正在运行从 javascript 到 Web 服务的 Ajax 调用:

 $.ajax(signingURI + "?fileName=" + fileName)
.done(function (data){
});

我的网络服务:

 [WebMethod]
public string PolicyGenerator(string fileName){
return "{\"res\":\"asdasda\"}" ;
}

检查数据参数时,我得到一个 XML 文档对象而不是 JSON。我做错了什么?

在监视表达式中:

data: document
URL: ""
anchors: HTMLCollection[0]
applets: HTMLCollection[0]
baseURI: null
body: null
characterSet: null
charset: undefined
childNodes: NodeList[1]
compatMode: "CSS1Compat"
constructor: DocumentConstructor
cookie: [Exception: DOMException]
defaultCharset: undefined
defaultView: null
......

最佳答案

如果您想使用 HTTP GET,请使用 ScriptMethod 修饰您的 Web 服务方法。 .

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string PolicyGenerator(string fileName){
return "{\"res\":\"asdasda\"}" ;
}

此外,不要在交易的任一端手动构建 JSON。 jQuery 为您序列化对象。

$.ajax({
...
data: { fileName: 'test.jpg' }
});

通过 GET 请求,数据 将被序列化为查询字符串。使用 POST,它以标准 x-www-form-urlencoded 样式在请求实体主体中发送。如果您想在 POST 正文中发送 JSON,请使用 JSON.stringify

您的服务器端函数应该返回一个可序列化的类。 .NET 将为您输出正确的 JSON。

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public PolicyGeneratorResponse PolicyGenerator(string fileName){
return new PolicyGeneratorResponse(...);
}

...

class PolicyGeneratorResponse {
public string res;
}

关于c# - 从 Javascript 调用 Web 服务时使用文档对象而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22210176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com