Ajax成功事件在调用服务时不会触发
问题描述:
我正在使用JQuery为本地服务创建AJAX。我的本地服务是一个HttpHandler(例如,Request.ashx)。在Request.ashx中,负责调用外部网站(例如CallExternalWebsite())。 CallExternalWebsite()使用.NET的System.Net.WebRequest()来发起请求。访问外部网站时,不会触发成功或错误事件。 (注:我也试过这个在IIS托管的WCF服务,我看到了同样的结果)Ajax成功事件在调用服务时不会触发
这里有两种情况:
此方案的工作原理:
- 在的ProcessRequest( ),注释掉 callExternalWebsite()。
- 对于对象o,用数据初始化以模拟结果。
- 点击myButton
- 成功事件触发客户端。
- 在Fiddler中,我可以看到标题信息。我看到JSON结果等
此方案不起作用:
- 在的ProcessRequest(),使呼吁callExternalWebsite()。
- 对于对象o,callExternalWebsite()将返回一个适当的对象。
- 点击myButton
- 成功事件不会在客户端触发。
- 在Fiddler中,我可以看到标题信息。我看到Json结果等。
- 我知道callExternalWebsite()正在工作,因为我已将结果发送到我的手机。
总结起来,HttpHandler中的外部http调用正在影响Ajax成功事件。
这里是AJAX调用的代码段: (我尝试不同的interations)
$(document).ready(function() {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
在HttpHandler的Request.ashx,
public Void ProcessRequest(httpContent context)
{
// Do some stuff....
// Make call to external web site
object o = callExternalWebsite (Uri, Data, "POST");
// Return results from callOtherWebsite
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(o);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
有什么想法?
谢谢。
史蒂夫
答
如果你这样做,味精VS msg.d会发生什么:
$(document).ready(function() {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg.d);
},
error: AjaxFailed
});
});
});
确定的响应是HTTP 200/OK?我相信只有2xx的状态码才算是“成功” – 2012-04-13 13:20:39
请将代码发布到'AjaxSucceeded'?也许那里有问题。尝试将成功调用更改为alert(“hello!”)或类似的命令,以确认成功分支未执行。 – 2012-04-13 13:26:07
我将成功改为: 'success:function(msg){alert(“hello”); }' 但仍然没有执行。 以下是来自Request.ashx调用的响应: HTTP/1.1 200 OK Cache-Control:private Content-Type:application/json; x-AspNet-Version:4.0.30319 X-Powered-by:ASP.NET 日期:2012年4月13日星期五16:28:40 GMT Content-长度:84' 一切似乎很好。 – Steve 2012-04-13 16:31:27