简体   繁体   English

如何通过ajax传递json数据?

[英]How to pass json data via ajax?

I am working a visual studio 2012 MVC program. 我正在使用Visual Studio 2012 MVC程序。

I use ajax to send data to a controller and wish the controller returns a body of html. 我使用ajax将数据发送到控制器,并希望控制器返回html正文。 the data is in json format. 数据为json格式。 the data is a string name and decimal TotFees. 数据是字符串名称和十进制TotFees。

I found that the parameters value in the public ActionResult ImmPay(string Name) in the controller are always null. 我发现控制器的公共ActionResult ImmPay(string Name)中的参数值始终为null。 Finally I tried just to pass name, but the value of name in the controller side is still null. 最后,我尝试仅传递名称,但是在控制器端,名称的值仍为null。

what is wrong in my code, and how to solve the problem? 我的代码有什么问题,以及如何解决该问题? Thank you. 谢谢。

View:
    function ImmPay()
    {
        var name = "ASP";
        var TotFees = 100.01;       

        //var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "\'}"; 
        //var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "m\'}";

        dd = "{\'b\':\'" + b + "\'}";
        dd = JSON.stringify(dd);
        $.ajax({
            url: '@Url.Action("ImmPay", "Consult")',
            type: 'GET',
            async: true,
            data: dd,
            contentType: 'application/json',
            context: document.body,
            success: function (response, textStatus, jqXHR) {
                $("#dialog-immpay").html(response);
                $("#dialog-immpay").dialog("open");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus);
            },
            complete: function () {
                ;
            }
        });

    }

Controller:
        public ActionResult ImmPay(string Name)
        {
        do something here
        }

JSON.stringify接受一个对象或数组并将其转换为JSON,因此您可以将数据构建到一个对象中并像这样对其进行字符串化

dd = JSON.stringify({b: b});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM