[英]Document object instead of JSON when calling webservice from Javascript
I am running an Ajax call from javascript to a webservice: 我正在运行从javascript到Web服务的Ajax调用:
$.ajax(signingURI + "?fileName=" + fileName)
.done(function (data){
});
My webservice: 我的网络服务:
[WebMethod]
public string PolicyGenerator(string fileName){
return "{\"res\":\"asdasda\"}" ;
}
When inspecting the data argument I get a XML document object instead of JSON . 检查数据参数时,我得到一个XML文档对象而不是JSON 。 What I am doing wrong? 我做错了什么?
In the watch expression: 在手表表达式中:
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
......
If you want to use HTTP GET, decorate your webservice method with ScriptMethod
. 如果要使用HTTP GET,请使用ScriptMethod
装饰您的webservice方法。
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string PolicyGenerator(string fileName){
return "{\"res\":\"asdasda\"}" ;
}
Also, don't manually construct JSON on either end of your transaction. 另外, 请勿在交易的任何一端手动构造JSON 。 jQuery serializes objects for you. jQuery为您序列化对象。
$.ajax({
...
data: { fileName: 'test.jpg' }
});
With GET requests, the data
will be serialized onto a query string. 使用GET请求, data
将被序列化到查询字符串上。 With POST, it is sent in the request entity body in standard x-www-form-urlencoded style. 使用POST,它将以标准x-www-form-urlencoded样式在请求实体主体中发送。 If you want to send JSON in the POST body, use JSON.stringify
. 如果要在POST正文中发送JSON,请使用JSON.stringify
。
Your server-side function should return a serializable class. 您的服务器端函数应返回一个可序列化的类。 .NET will output proper JSON for you. .NET将为您输出正确的JSON。
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public PolicyGeneratorResponse PolicyGenerator(string fileName){
return new PolicyGeneratorResponse(...);
}
...
class PolicyGeneratorResponse {
public string res;
}
Try adding a dataType to the request: 尝试将dataType添加到请求中:
$.ajax(signingURI + "?fileName=" + fileName, { dataType: 'json' })
.done(function (data){
});
Something is very weird going on. 发生的事情很奇怪。 Seems that the webservice does return JSON, but when I used the .done
callback I couldn't read it. 似乎Web服务确实返回JSON,但是当我使用.done
回调时,我无法读取它。
$.ajax({
type: "POST",
url: signingURI,
data: "{'fileName':'" + encodeURI('test.jpg') + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg){
Using the success callback inside the other properties gave me JSON. 在其他属性中使用成功回调给了我JSON。 So weird, or is it?. 好奇怪,还是?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.