2015-06-29 28 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