[英]get response from XMLDocument in web service in javascript Ajax call…?
[英]how to call web service from javascript (ajax)
我有 1 个项目 webservice 和 1 个项目 web asp.net 我想通过 json(ajax) 插入数据我通过代码测试了文件服务,它很好,代码 js 文件 WebService1 有错误:
public bool HelloWorld(student obj) {
SqlConnection cnn = new SqlConnection("Data Source=PHAMHOP-LAPTOP\\SQLEXPRESS;Initial Catalog=qlsv;Integrated Security=True");
cnn.Open();
SqlCommand cmd = new SqlCommand("insert into sinhvien(name,age) values(@name,@age)", cnn);
cmd.Parameters.AddWithValue("name", obj.name);
cmd.Parameters.AddWithValue("age", obj.age);
int row = cmd.ExecuteNonQuery();
if (row == 1){
return true;
} else {
return false;
}
}
文件aspx:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function add() {
$.ajax({
type: "POST",
url: "http://localhost:51097/Service1.asmx/HelloWorld",
data: "{'id':'1' ,'name': 'Amit', 'age': '97'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("ok");
}
});
}
</script>
<body>
<input type='Button' value='gui' OnClick='add()'/>
</body>
这是行不通的。
由于返回的数据不是JSON
contentType: "application/json; charset=utf-8", dataType: "json",
因此不需要contentType: "application/json; charset=utf-8", dataType: "json",
并且data
选项不需要是字符串。 将其作为对象传递。
尝试这个
function add() {
$.ajax({
type: "POST",
url: "http://localhost:51097/Service1.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
id: 1,
name: 'Amit',
age: 97
},
success: function (msg) {
alert("ok");
}
});
}
或者,您可以尝试将 JSON 作为字符串参数而不是作为学生传递,并使用 Newtonsoft 或 System.Web.Script.Serialization.JavaScriptSerializer 自己反序列化它。
bool HelloWorld(string obj)
代替
bool HelloWorld(student obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.