2015-05-07 19 views
0
工作

所以我有一个基本的控制器接受后..MVC的jQuery Ajax的帖子 - 只能让它使用硬编码值

[HttpPost] 
    public ActionResult Submit(string postCost) 
    { 
     //Do stuff here before sending back redirect details... 

     return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") }); 
    } 

而且我通过jQuery AJAX方法发布:

$.ajax({ 
    url: partyURL, 
    dataType: 'json', 
    contentType: 'application/json', //charset=utf-8', 
    type: 'POST', 
    data: { postCost: postageCost}, //**This fails!** 
    //data: "{'postCost':'3.50'}", //**This works** 
    success: function (response) { 

     if (response.result == 'SoldOut') { 
      $("#soldOut").show(); 
     } 
     else if (response.result == 'Redirect') { 
      //All good, onward to confirmation page 
      window.location = response.url; 
     } 
    }, 
    error: function (xhr, status, error) { 
     // Error handling here 
    } 
}); 

其中postageCost变量在失败时返回状态500发送:

postageCost = '3.50'; 
postageCost = JSON.stringify(postageCost); //also fails with this 

但如果我硬编码数据定义一个s

data: "{'postCost':'3.50'}", 

它工作正常。

因此,关键在于我在处理数据元素?

+0

检查返回的错误网络选项卡。 (并且你有没有试过'data:JSON.stringify({postCost:postageCost}),' –

+0

@StephenMuecke - data:JSON.stringify({postCost:postageCost})如果你发布答案,你可以有糖果。谢谢:) –

+0

厄齐尔刚刚发布了一个答案,所以你可以接受(尽管你不需要'postCost'周围的引号)。作为一个方面说明,为什么你的方法参数不是'(小数postCost)'? –

回答

2

你需要做的

var datum = {'postCost': '3.50'}; 
data: JSON.stringify(datum), //Ajax call data 
+0

谢谢厄齐尔:)我还没意识到你可以在数据段中串联。 –