2015-06-29 24 views
0

我的ajax請求返回成功,但數據似乎並沒有在那裏。我知道json序列化的工作原理,因爲如果我對數據庫執行查詢並對其進行序列化,則查詢結果會正確返回。在下面的情況下,我回來的是「[]」。控制器沒有收到阿賈克斯請求

編輯:我也做其他測試,如嘗試從itemsInCart提取單個數據片,它似乎是完全空的(這證明我得到的迴應)。

型號:

public class ItemInCart 
{ 
    [Key] 
    public int ItemId { get; set; } 
    public virtual Variety variety { get; set; } 

    public int Quantity { get; set; } 
    public virtual InventoryItem inventoryItem { get; set; } 

    public double Price { get; set; } 
    public virtual Variety price { get; set; } 

} 

控制器:

[HttpGet] 
    public ActionResult completeSale(List<ItemInCart> itemsInCart) 
    { 
     var json = new JavaScriptSerializer().Serialize(itemsInCart); 
     return Json(json, JsonRequestBehavior.AllowGet); 
    } 

阿賈克斯:

$.ajax({ 
    type: "GET", 
    url: "/" + current_controller + "/completeSale", // the method we are calling 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    data: { "itemsInCart": itemsInCart }, 
    success: function (result) { 
     alert("success " + JSON.stringify(result)); 
    }, 
    error: function (result) { 
     alert("failed " + result); 
    } 

}); 

請求URL(從開發者工具):

http://localhost:52459/Sale/completeSale?itemsInCart=[{"ItemId":1,"Quantity":"1","Price":3.5}] 
+0

你試過'警報( 「成功」 + result.quantity)完整路徑;'? –

+0

您的內容類型與您要發送的數據不符。 '{「itemsInCart」:itemsInCart}'是一個對象,而不是json。我建議刪除contentType選項。 –

+0

'result.quantity' =>'undefined' – abalter

回答

0

首先,您不要向GET請求提交數據。

其次,試試這個

$.ajax({ 
     type: "GET", 
     url: "http://localhost:59945/wmain/completesale", // the method we are calling 
     contentType: "application/json; charset=utf-8", 

     dataType: "json", 
     success: function (result) { 
      var v = JSON.parse(result); 
      alert(v.name); 
      alert('Yay! It worked!tim' + result); 

      // Or if you are returning something 

     }, 
     error: function (result) { 
      alert('Oh no aa>>>> :(' + result.responseText); 
     } 
    }); 

指定在瀏覽器中打開了

+0

是的,我應該POST,但是在POST中你看不到你實際發送了什麼,所以它很難調試。是的,這是有效的。而且,的確,我在發送單個對象方面取得了很好的成功。但是對象列表不起作用。 – abalter