使用ajax调用.net,C#在客户端获取服务器端的字符串值
本文关键字:服务器端 获取 字符串 客户端 调用 ajax net 使用 | 更新日期: 2023-09-27 18:15:33
我正在创建一个.net应用程序。我只是想在ajax调用中得到这个"嗨"字符串。我需要做什么?现在我一直都不确定。没有别的。
我的客户端脚本看起来像blow
<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";
}
更新:
问题解决了
这是造成这些问题的一个小错误。问题出在"contenttype"answers"datatype"上。两种类型的"t"都应该是大写字母。ie"contentType"answers"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"answers"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>