我一直在试图解决我的问题与此answer,但我没有运气。总的来说,我创建了一个WCF项目,其中有许多我想通过AJAX访问的函数(通过我的html页面中的javascript)。Ajax请求WCF数据(以JSON格式),但成功的消息到达错误
这里是我的Web服务中的函数的例子:
iService
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
string GetStuff();
服务
public string GetStuff()
{
string url = string.Format("http://myapi.co.uk/api/mystuff");
WebRequest myReq = WebRequest.Create(url);
// Where USERNAME and PASSWORD are constants
string usernamePassword = USERNAME + ":" + PASSWORD;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(USERNAME, PASSWORD));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
return content;
}
请注意,我也尝试返回Stream
直接还。
在我的javascript和ajax!
function getData()
{
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: "http://localhost:15574/Service1.svc/GetStuff",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(result) {
alert(result);
},
error: function(msg) {
alert("Fail: " + msg.status + ":" + msg.statusText);
}
});
}
我打的错误部分,但奇怪的是有一个成功的错误信息......
我本来以为这个问题是因为从外部API的JSON格式不正确,但我试着改变我的web服务来返回一些完全有效的JSON,并显示相同的错误。就像我之前提到的,我试图改变我的web服务来返回流,但我没有运气。
任何与此有关的帮助将不胜感激,我将非常感激。
更新
附:它似乎在WCF测试客户端中正常工作,返回一个字符串与我所期望的。
PPS只是增加了一个参数的误差函数来获得它的地位,我越来越parsererror
PPPS传递给误差第三个参数是jquery171014696656613195724_1341477967656 was not called
哪里是GetStuff方法的实现,以解决这一问题? –
我的歉意!通过复制不同的功能! – ThePower