如何调用jquery ajax到c#页面
本文关键字:ajax 页面 jquery 何调用 调用 | 更新日期: 2023-09-27 17:50:52
如何调用jquery ajax到c#页面在visual studio中没有响应通过断点尝试
首先尝试了Big one, c#端(ProfitCentersNameInsert)函数没有响应,然后尝试了另一个简单类型(apply)函数,但两个方法都没有响应刚刚在Ajax上注释了下面几行
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
JS代码$(function() {
profit.onRefresh()
$( "#btnAdd" ).click(profit.onClickSave);
});
var profit = {
onRefresh: function(){},
onClickSave: function(){
var ProfitCenterName =$('#txtProfitCenter').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
url: "ProfitCentersScreen.aspx/apply",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
data:'{}',
async: false,
success: function (response) {
alert( response );
alert(ProfitCenterName);
$('#txtProfitCenter').val('');
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
}
};
c#代码[WebMethod]
public static string ProfitCentersNameInsert(string ProfitCenterName)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=192.168.0.133;User Id=hll; " + "Password=hll;Database=checking_DB;"); //+ "Pooling=true;MaxPoolSize=100;Timeout=20;"
try
{
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("Insert into tbl_Profit_Centers(Profit_Center_Id,Profit_center_Name) Values(default,@ProfitCenterName)", conn);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@ProfitCenterName", ProfitCenterName);
command.ExecuteNonQuery();
conn.Close();
return "Success";
}
catch (Exception ex)
{
return "failure";
}
}
[WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
试试这个
url: "ProfitCentersScreen.aspx",
data: {ProfitCenterName: ProfitCenterName}
尝试以下几点,应该可以工作:
1)如果你的页面是在项目的根级,那么url应该像下面这样:
url: "/ProfitCentersScreen.aspx/apply"
或
url: "../ProfitCentersScreen.aspx/apply"
2)字符串化参数
data: JSON.stringify({})
3)最后添加参数
dataType: "json",
尝试在你的成功中使用response.d
success: function (response) {
alert(response.d);
alert("Record saved successfully..!!");
},
下面是一个简单的jQuery Ajax调用的伪代码
jQuery: $("#bntAJax").on('click', function (e) {
$.ajax({
type: "POST",
// your webmethod
url: "AjaxFunction/myFunction.asmx/apply",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall() {
}
e.preventDefault();
});
WebMethod:
[WebMethod]
public string apply()
{
return "Hello";
}