javascript - MVC jQuery Ajax Post - 只能让它使用硬编码值

标签 javascript jquery ajax asp.net-mvc-4

所以我有一个基本的 Controller 接受帖子..

    [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
    }
});

失败返回​​状态 500 时发送的 postageCost 变量:

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

但是如果我将数据定义硬编码为

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

效果很好。

因此,关键一定在于我对数据元素所做的事情?

最佳答案

你需要做

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

关于javascript - MVC jQuery Ajax Post - 只能让它使用硬编码值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098628/

相关文章:

javascript - 动态 PDF 并打开新窗口而不是下载

javascript - 为什么我的移动菜单项在点击时不显示?

javascript - 平移多个 Y 轴之一以获取 Highcharts

javascript - 闭包(let 关键字)- Javascript

javascript - 使用sapui5的日期过滤器

javascript - PHP - 将隐藏值传递给 jquery

javascript - JQuery http GET 用于通过外部 ID 获取记录

jQuery:选择align = "center"的元素

javascript - 发送 JSON stringify 到 PHP 如何读取它

jquery - 使用 jQuery .load 将行添加到 html 表