我有一个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);
},
});
});
});
2015-10-15
Raj Gola
+0
请提供一些更多的细节,并显示为代码剪断,而不是整个程序。 –
+0
您的数据对象属性名称与您webmethod的启动项不匹配。 –
+0
同样在您的成功中,您检查webmethod是否返回'true',但它实际上会返回成功消息。 –