2016-07-16 230 views
2

我在這個論壇和其他人看了很多關於這個問題的答案,代碼看起來不錯,但問題仍然存在。當我做POST請求時,我得到400錯誤代碼(錯誤的請求)。但是當我從POSTMAN客戶端調用相同的資源時,我成功地得到了迴應。任何人都可以看看我的代碼,看看我做錯了什麼。Ajax POST請求不起作用

public class Country{ 

    int id; 
    String countryName; 

    @JsonCreator 
    public Country(@JsonProperty("id")int id, @JsonProperty("countryName")String countryName) { 
     this.id = id; 
     this.countryName = countryName; 
    } 
    ....setter/getters 
    } 

REST控制器的文件

@RestController 
    public class CountryController { 
     static List<Country> listOfCountries = new ArrayList<Country>(); 
     static{ 
      createCountryList(); 
     } 
     @RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json") 
     public List<Country> getCountries() 
     { 
      return listOfCountries; 
     } 

     @RequestMapping(value = "/addCountry", method = RequestMethod.POST,headers="Accept=application/json") 
     public List<Country> addCountry(@RequestBody Country country) 
     {System.out.println("addcountry called"+country); 
      listOfCountries.add(country); 
      return listOfCountries; 
     } 

     @RequestMapping(value = "/country/{id}", method = RequestMethod.GET,headers="Accept=application/json") 
     public Country getCountryById(@PathVariable int id) 
     { 

      for (Country country: listOfCountries) { 
       if(country.getId()==id) 
        return country; 
      } 

      return null; 
     } 

    // Utiliy method to create country list. 
     public static List<Country> createCountryList() 
     { 
      Country indiaCountry=new Country(1, "India"); 
      Country chinaCountry=new Country(4, "China"); 
      Country nepalCountry=new Country(3, "Nepal"); 
      Country bhutanCountry=new Country(2, "Bhutan"); 

      listOfCountries.add(indiaCountry); 
      listOfCountries.add(chinaCountry); 
      listOfCountries.add(nepalCountry); 
      listOfCountries.add(bhutanCountry); 
      return listOfCountries; 
     } 
    } 

JS文件內容

$(function() { 
     var $ords = $('#orders'); 
     var $cid = $('#cid'); 
     var $name = $('#name'); 

     function displayOrder(country){ 
      $ords.append('<li>Id :' + country.id + ',name : '+ country.countryName + '</li>'); 
     } 
     $.ajax({ 
        type : 'GET', 
        url : 'http://localhost:8080/SpringRestfulWebServicesWithJSONExample/countries', 

        success : function(data) { 
         // data = JSON.parse(data); 
         $.each(data, function(i, country) { 
          displayOrder(country); 
         }); 
        }, 
        error : function() { 
         alert("error loading data"); 
        } 
       }); 
     $("#add").on("click", function(){ 
      var country= { 
        id:$cid.val(), 
        countryName:$name.val() 
      }; 
      $.ajax({ 
       type : 'POST', 
       url : 'http://localhost:8080/SpringRestfulWebServicesWithJSONExample/addCountry', 
       data:country, 
       contentType: "application/json", 
       success : function(newData) { 
        // data = JSON.parse(data); 
        $.each(newData, function(i, country) { 
         displayOrder(country); 
        }); 
       }, 
       error : function() { 
        alert("error loading data"); 
       } 
      }); 
     }); 
    }); 

HTML網頁的相關部分

<body> 
    <h2>Country Names</h2> 
    <ul id="orders"> 
    </ul> 
    <p>Id: <input type="text" id="cid"></p> 
    <p>Name: <input type="text" id="name"></p> 
    <button id="add">Add</button> 
</body> 
+0

如果頁面是您需要實現服務器CORS不同的端口上。查看瀏覽器開發工具控制檯會看到CORS錯誤 – charlietfl

+0

不,頁面正在8080上運行,並且服務控制器也在同一端口上運行。 – Surinder

+0

檢查瀏覽器開發工具網絡中的實際請求以準確查看發送的內容 – charlietfl

回答

0

你沒有發送JSON。設置的contentType不會自動轉換數據到JSON,你需要自己的序列化

變化:

data:country, 

data:JSON.stringify(country), 
+0

哇,這很快,非常感謝,它工作正常! – Surinder

0

代碼的此位看起來我錯了。

var country = { 
       id:$cid.val(), 
       countryName:$name.val() 
       }; 

我會寫它是這樣的:

var id = $cid.val(), 
    countryName = $name.val(); 

var country = { 
    "id":id, 
    "countryName":countryName 
} 

使用雙引號idcountryName的是POST請求重要。

+0

除非在名稱中使用特殊字符,否則引號在對象鍵中不重要。首先爲值創建變量也沒有影響。對象本身在被髮送之前被序列化 – charlietfl

+0

感謝您的回覆。這段代碼來自codeAcademy教程。無論如何,我做了你所建議的改變,但仍顯示相同的錯誤。 無法加載資源:服務器響應的狀態爲400(錯誤請求 – Surinder