繁体   English   中英

使用Ajax调用.net,C#获取客户端的服务器端字符串值

[英]Get server side string value in client side using ajax call .net,C#

我正在创建一个.net应用程序。 我只是想在我的ajax调用中获取此“ Hi”字符串。 我需要做什么? 现在,我一直都处于不确定状态。 没有其他的。

我的客户端脚本看起来像打击

    <script type = "text/javascript">
    $(document).ready(function () {
        $('.cart').click(function () {
            var id = $(this).attr('id');
            CallAddCart(id);
        });
    });
    function CallAddCart(ItemId) {
        $.ajax({
            type: "POST",
            url: "SearchParts.aspx/AddShopCart",
            data: '{ItemId: "' + ItemId + '"}',
            contenttype: "application/json; charset=utf-8",
            datatype: "json",
            success: function (data) {
                OnSuccess(data);
            },
            failure: function (response) {
                alert(response.d);
            }
        });
   }

   function OnSuccess(response) {
       alert('On sucess' + response);
       alert(response);
   }         
</script>

我的服务器端看起来像

    [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string AddShopCart(string ItemId) 
    { 
       return "Hi";
    } 

更新:

问题解决了

那是导致这些问题的一个小错误。 问题出在“内容类型”和“数据类型”上。 两种类型的“ t”均应使用大写字母。 即“ contentType”和“ dataType” :)现在可以获取Hi了:)

我建议以JSON类型返回值

[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddShopCart(string ItemId) 
{
   var result = new { d = "Hi" };
   return JsonConvert.SerializeObject(result);
} 

用JavaScript

success: function (data) {
   OnSuccess(data.d);
}
[WebMethod]
public static string AddShopCart(string ItemId)
{
    return "Hi";
}

去掉它。 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

用JavaScript

success: function (data) {
   OnSuccess(data.d);
}

图片来源: http//www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

引起问题的区分大小写。 在下面的脚本中,我使用正确的用法进行了更新

以前是“ contenttype”和“ datatype”。 现在更改为contentType和dataType

<script type = "text/javascript">
$(document).ready(function () {
    $('.cart').click(function () {
        var id = $(this).attr('id');
        CallAddCart(id);
    });
});
function CallAddCart(ItemId) {
    $.ajax({
        type: "POST",
        url: "SearchParts.aspx/AddShopCart",
        data: '{ItemId: "' + ItemId + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            OnSuccess(data);
        },
        failure: function (response) {
            alert(response.d);
        }
    });
 }

 function OnSuccess(response) {
   alert('On sucess' + response);
   alert(response);
   }         
  </script>

暂无
暂无

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

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