我试图通过jQuery调用webservice,但它没有显示任何结果或错误。我的代码是:
<script type="text/javascript" language="javascript">
var empId = '<%= Session["UserName"] %>';
</script>
<script type="text/javascript">
alert(empId);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "ServiceGetUser.asmx/GetEmployee",
data: "{'employeeId': '" + empId + "'}",
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
}
});
</script>
我从session
获取一个值,然后将其成功打印,然后将其传递给网络服务,并返回打印名称Jane Developer
,如我的网络服务代码所示:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace MentorMentee
{
/// <summary>
/// Summary description for ServiceGetUser
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ServiceGetUser : System.Web.Services.WebService
{
[WebMethod]
public string GetEmployee(string employeeId)
{
return "Jane Developer";
}
}
}
对你的建议抱有什么错误
由于
答案 0 :(得分:2)
您可以将其放在doc ready block
:
$(window).load(function(){
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "ServiceGetUser.asmx/GetEmployee",
data: {'employeeId': '<%= Session["UserName"] %>'}, //<-- try it
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
}
});
});
答案 1 :(得分:1)
dataType以json的形式给出。这意味着jquery会将从服务器收到的响应解析为json。但是你在服务中返回字符串。所以jQuery会抛出解析错误。
尝试附加complete(jqXHR jqXHR, String textStatus)
回调。并查看textStatus
尝试使用
<script type="text/javascript" language="javascript">
var empId = '<%= Session["UserName"] %>';
</script>
<script type="text/javascript">
alert(empId);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "ServiceGetUser.asmx/GetEmployee",
data: "{'employeeId': '" + empId + "'}",
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
} ,
complete: function(xhr, textStatus) {
alert(textStatus);
}
});
</script>
答案 2 :(得分:0)
试试这个:
<script type="text/javascript" language="javascript">
var empId = '<%= Session["UserName"] %>';
</script>
<script type="text/javascript">
alert(empId);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "ServiceGetUser.asmx/GetEmployee",
data: '{employeeId: "' + $("#<%=employeeId.ClientID%>")[0].value + '" }',
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
}
});
</script>
答案 3 :(得分:0)
首先尝试将你的json字符串化
alert(JSON.stringify(data))
那么也许你可以找到你的错误..