2011-11-29 145 views
2

朋友,我迷失在這裏。jQuery .ajax()函數總是返回錯誤

我有這樣的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/

,它表明我,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); 
       // }); 
      } 
        }); 

有人有一些想法?

+1

請記住,如果調用跨域你有使用jsonp! – RvdK

+0

是的,你的是正確的 – quicoli

回答

0

問題是跨端腳本。這可以通過使用'jsonp'作爲dataType很容易地解決。 然後改變網站使用的是已被添加到該呼叫「「?回調=」和包裝,圍繞JSON。例如,如果callback = 'test'

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

朋友,真的很感謝你!因爲我使用WCF 4,我只需要更改我的web.config接受跨端([鏈接] http://stackoverflow.com/questions/1178614/return-json-wrapped-in-a-callback-function-from-a-wcf-rest-web- service [/ link]),當然也可以使用jsonp。再一次,謝謝! – quicoli

0

Link for the description
status === 0 - XHR狀態,是初始化或沒有,這意味着用戶處於脫機狀態。

在執行跨站點腳本(訪問被拒絕)或請求無法訪問的URL(錯字,DNS問題等)時,您會看到狀態爲0。

+0

用戶必須使用JSONP的。基本上這是包裝返回的JSON在一個函數調用的方式 – RvdK