我正在尝试通过jQuery调用网络服务,但未显示任何结果或错误。我的代码是:

<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成功打印它得到一个值,然后将其传递到webservice,并返回打印名称Jane Developer,如我的webservice代码所示:

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";
        }
    }
}


出了什么问题希望您提出建议

谢谢

最佳答案

您可以将其放在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.");
      }
    });
 });

关于javascript - $ .ajax不调用ASP.Net中的WebService,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14728856/

10-11 05:21