简体   繁体   English

无法通过Java脚本方法传递Ajax发布

[英]unable to pass ajax post in java script method

i came across with a minor conflict while i am reading the html image value and passing value data in java script method works fine, and in ajax POST to pass the value towards controller, and unforunelty ajax point the controller over break point but the string Country parameter is null (passing a null value =), may i know the reason why please ! 我在读取html图像值并在java脚本方法中传递值数据时遇到了小冲突,并且在ajax POST中将值传递给控制器​​,但不幸的ajax将控制器指向断点,但字符串为Country参数为null(传递null值=),我可以知道为什么的原因! Thank you ! 谢谢 !

public ActionResult Prayer_Schedule(string Country){

}


<img src="~/images/flags/india.jpg" value="india" onclick="choose(this);">

<script type="text/javascript">

    function choose(element) {
        var Country = element.getAttribute("value"); 
        $.ajax({
            type: 'POST',
            url: '../Home/Prayer_Schedule',
            data: {
                Country: Country,
            },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            cache: false,
            timeout: 100000,
            success: function (response) {
                alert('ajax success: ' + response);
                //location.href = "/thankyou.html";
            }
        });

You have to use jQuery.param for post 您必须使用jQuery.param进行发布

 data: jQuery.param({ Country: Country}),

Or use $.post 或使用$ .post

$.post('../Home/Prayer_Schedule', { Country: Country }, 

You have set contentType: 'application/json; charset=utf-8' 您已经设置了contentType: 'application/json; charset=utf-8' contentType: 'application/json; charset=utf-8' so you need to send json object or you can simply remove this to get value in controller. contentType: 'application/json; charset=utf-8'因此您需要发送json object ,也可以简单地将其删除以在控制器中获取值。

$.ajax({
        type: 'POST',
        url: '../Home/Prayer_Schedule',
        data: {
            Country: Country,
        },
        dataType: 'json',
        async: false,
        cache: false,
        timeout: 100000,
        success: function (response) {
            alert('ajax success: ' + response);
            //location.href = "/thankyou.html";
        }
    });

Also if you have not decorated your method with HttpPost you will need this too. 另外,如果您还没HttpPost装饰您的method ,那么您也将需要它。

[HttpPost]
public ActionResult Prayer_Schedule(string Country){

}

It may be your javascript on the getAttribute() function. 它可能是您在getAttribute()函数上的javascript。 You are using value, which isn't a valid attribute for an img tag. 您正在使用值,该值不是img标签的有效属性。 Try this instead, using data-* attributes: 使用data- *属性尝试以下操作:

<img src="~/images/flags/india.jpg" data-value="india" onclick="choose(this);">

then in your javascript: 然后在您的JavaScript中:

element.getAttribute("data-value");

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

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