2012-11-13 102 views
2

我在MVC4中創建了REST API,當我從提琴手撰寫請求時它工作正常。但在我的應用程序中,我需要通過jsonp調用,因爲它會跨域請求。但是,當我調用這個服務它給我的錯誤,如下圖所示:使用JSONP和JQuery調用REST API

jQuery的JSONP呼叫..

$.ajax({ 
     type: "POST" , 
     url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf&callback=?", 
     data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId }, 
     cache: false, 
     contentType: "application/json; charset=utf-8", 
     success: function (response) { 
      if (callback) 
       callback(response.d); 
     }, 
     error: function (response) { 
      if (callback) 
       error(response.d); 
     }, 
    }); 

錯誤: enter image description here

+0

也許這可能有所幫助:http://stackoverflow.com/questions/5241088/jquery-call-to-webservice-returns-no-transport-error – mipe34

+0

它不適用於JSONP –

回答

2

現在你是不是做JSONP。它仍然是POST請求。爲了使它成爲JSONP,你只需要簡單地將dataType: "jsonp"添加到你的$.ajax()調用中即可。你也可以刪除一些其他的冗餘參數,比如content-type和'callback'參數(但這是可選的)。所以,你的代碼應該looke像:

$.ajax({ 
    url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf", 
    data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId }, 
    datatype: "jsonp", 
    cache: false, 
    success: function (response) { /* ... */ }, 
    error: function (response) { /* ... */ }, 
}); 

也做好準備,你的請求將被轉化爲找一本看起來像 /GetDomainAvailability?apikey=key&callback=jquery123&SubDomain=sss&ParentDomain=ppp&ResellerId=123&_=4398572349857

因此,對於準備你的服務器端代碼。