【问题标题】:jQuery .ajax() function always returning errorjQuery .ajax() 函数总是返回错误
【发布时间】:2012-01-08 19:45:46
【问题描述】:

朋友们,我迷路了。

我有这个 WCF Rest 服务以 json 格式返回数据:http://189.126.109.249/ieptb/Cidades?uf=SP

我可以使用 asp.net Web 表单应用程序访问它,也可以使用 Windows Phone 应用程序访问它。但是我不能让它在一个简单的 jQuery.$Ajax() 调用下工作。我的 jQuery 总是返回错误。如果您查看我的代码,您会发现我有一个捕获错误的函数。

这是我正在使用的脚本:http://jsfiddle.net/n6sLQ/4/

我用 Fiddler 测试过,它显示 HTTP 响应为 200(ok),甚至显示返回的 json 数组,如下所示:

HTTP/1.1 200 OK
Via: 1.1 CM-SRV03
Connection: Keep-Alive
Proxy-Connection: Keep-Alive
Content-Length: 2360
Date: Tue, 29 Nov 2011 13:02:44 GMT
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
Cache-Control: private

[{"Nome":"AGUAS DE LINDOIA","Uf":"SP"},{"Nome":"AMERICANA","Uf":"SP"},{"Nome":"AMPARO","Uf":"SP"}]

我不知道我的 jQuery 出了什么问题...

  $.ajax({
            url: "http://189.126.109.249/ieptb/Cidades?uf=SP",
contentType:"application/json",
            dataType: "json",

            error: function (x, e) {
                if (x.status === 0) {
                    alert('You are offline!!\n Please Check Your Network. ' + x.reponseText);
                }
                else if (x.status == 404) {
                    alert('Requested URL not found.');
                } else if (x.status == 500) {
                    alert('Internel Server Error.');
                } else if (e == 'parsererror') {
                    alert('Error.\nParsing JSON Request failed.');
                } else if (e == 'timeout') {
                    alert('Request Time out.');
                } else {
                    alert('Unknow Error.\n' + x.responseText);
                }
            },
            success: function (cidades) {

               // $.each(cidades, function (indice, cidade) {
               //     alert(cidade.Nome + ": " + cidade.Uf);
               // });
            }
                    });

有人有想法吗?

【问题讨论】:

  • 记住,如果调用是跨域的,你必须使用jsonp!

标签: jquery


【解决方案1】:

Link for the description
status === 0 - xhr 状态,是否已初始化,表示 用户 处于离线状态。

在执行跨站点脚本(访问被拒绝)或请求无法访问的 URL(错字、DNS 问题等)时,您会看到状态 0。

【讨论】:

  • 用户确实必须使用 JSONP。基本上这是以函数调用的方式包装返回的 JSON。
【解决方案2】:

问题在于跨端脚本。这可以通过使用'jsonp' 作为数据类型轻松解决。 然后更改网站以使用已添加到调用中的 '"?callback=' 并将其包装在 json 周围。例如,如果 callback = 'test'

test('[{"Nome":"AGUAS DE LINDOIA","Uf":"SP"},{"Nome":"AMERICANA","Uf":"SP"},{"Nome":"AMPARO","Uf":"SP"}]')

【讨论】:

  • 朋友们,真的谢谢你们!当我使用 WCF 4 时,我只需要更改我的 web.config 以接受跨端 ( [link]stackoverflow.com/questions/1178614/… ),当然,还要使用 jsonp。再次感谢!
猜你喜欢
  • 2014-01-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
相关资源
最近更新 更多