我有一個web服務,並在其中有兩種方法(select
,insertdata
)。我想用jquery在sql中插入一條記錄。我怎樣才能做到這一點?我已經制作了該代碼,但它不起作用。請幫助我。我如何添加項目在sql中使用jQuery(ajax)通過web服務
我的web服務
Sqlconeection dd = new Sqlconeection();
int rowsInserted = 0;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string insertRecord(Int64 mbn,string name,double amt,bool Notify)
{
SqlConnection connection = dd.getconnection();
SqlCommand cmd = new SqlCommand("InsertData");
cmd.Connection = connection;
if (connection.State == ConnectionState.Closed)
connection.Open();
// string inser = "insert into expensive(mobileNumber,Name,Amount,Notify)values('" + mbn + "','" + name + "','" + amt + "','" + Notify + "')";
//cmd.CommandText = inser;
cmd.Parameters.AddWithValue("@mobile", mbn);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Amount", amt);
cmd.Parameters.AddWithValue("@Notify", Notify);
cmd.CommandType = CommandType.StoredProcedure;
rowsInserted= cmd.ExecuteNonQuery();
return string.Format("Thank you, {0} number of rows inserted!", rowsInserted);
}
[WebMethod(Description = "Returns all Products")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public DataTable selectdata(Int64 mnb)
{
DataTable dt = new DataTable();
SqlConnection conn = dd.getconnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
if (conn.State == ConnectionState.Closed)
conn.Open();
string select = "select mobileNumber,Name,Amount,Notify from expensive where mobileNumber='" + mnb + "'";
cmd.CommandText = select;
SqlDataReader dr = cmd.ExecuteReader();
dt.TableName = "expensive";
dt.Load(dr);
return dt;
}
我API代碼
$(function() {
$('#btnSubmit').click(function() {
var mob = $('#txtmo').val();
var Nm = $('#txtName').val();
var amout = $('#txtAmt').val();
var notify = $('#txtnoty').val();
$.ajax({
type: "POST",
url: "InsertData.asmx/insertRecord",
data: "{ mob: '" + mob + "', Nm: '" + Nm + "',amount:'" + amout + "',notify:'" + notify + "'}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#txtmo').val('');
$('#txtName').val('');
$('#txtAmt').val('');
$('#txtnoty').val('');
$('#lblData').html(JSON.stringify(data.d));
}
},
error: function (r) {
console.log(r);
},
});
});
});
請提供一些更多的細節,並顯示爲代碼剪斷,而不是整個程序。 – Sojtin
您的數據對象屬性名稱與您webmethod的啓動項不匹配。 – kmcoulson
同樣在您的成功中,您檢查webmethod是否返回'true',但它實際上會返回成功消息。 – kmcoulson