2013-03-04 40 views
0

讓我首先說我不是非常熟悉Javascript,我無法弄清楚這裏發生了什麼。jquery沒有正確序列化json在ajax調用

我有以下功能:

 self.search = function() { 

      var searchTerms = { 
       "City": this.cityName, 
       "State": this.stateName, 
       "StoreNumber": this.storeNumber, 
       };     


       $.ajax("/api/SearchApi", { 
        data: searchTerms, 
        type: "POST", contentType: "application/json", 
        success: function (result) { 
         alert(result);        
         } 
        } 
       }); 

當我提交,會發生什麼情況是不提交一個很好的JSON對象,如預期,它提交一個JSON反對格式化爲這樣:"City=testing&State=AL&StoreNumber=test "

理想我想使用GET方法將對象傳遞給我的服務器,以便我可以返回結果,但是當我使用get方法時,它只是將上述內容附加到API調用url,從而導致URL請求形成如下: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test

任何幫助,將不勝感激。

回答

2

請確保您將JSON的dataType添加到您的$.ajax({ });對象。這應該解決問題!

$.ajax({ 
    // ... 

    data  : JSON.stringify(searchTerms), // Encode it properly like so 
    dataType : "json", 

    // ... 
}); 
+0

'JSON.stringify(searchTerms),//只是爲了好measure'是如果他希望服務器以JSON的形式接收數據,實際上是必需的。 +1 – 2013-03-04 18:43:37

+0

謝謝。我刪除了contentType:「application/json」,並用dataType替換它,它的工作非常好。感謝你的幫助。 – 2013-03-04 18:45:36

+1

@RaySülzer'contentType'用於返回**'數據',您將從成功中獲得回報(如果有的話),幾乎已經有了! – 2013-03-04 18:48:49

1

兩件事情

  1. json的內容類型(而不是數據類型)添加到您的Ajax對象注意重要的是你的服務器在這種情況下,UTF-8使用的字符集。

  2. 使用Json2圖書館字符串化和解析JSON發送和接收時,它可以在這裏找到:https://github.com/douglascrockford/JSON-js/blob/master/json2.js

    $.ajax({ 
        url: URL, 
        type: "POST", 
        //Stringify the data you send to make shure its properly encoded 
        data: JSON.stringify(DATA), 
        //This is the type for the data that gets sent    
        contentType: 'application/json; charset=utf-8', 
        //This is for the data you receive 
        dataType: "json" 
    }).done(function(data) { 
        var dataYouGet = JSON.parse(data); 
    }).fail(function(xhr, ajaxOptions, thrownError) { 
    
    }).always(function(data) { 
    
    });