【问题标题】:Ajax call failing to consume the WCF restful serviceAjax 调用未能使用 WCF RESTful 服务
【发布时间】:2014-06-19 14:29:57
【问题描述】:

我有一个WCF restful 服务,它向外界公开登录方法定义如下,它只是使用数据库(登录表)验证给定的用户凭据并以json 格式返回结果

C# 代码:

[OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "login/{sUserID}/{password}")]
    List<ParkingLotRestWCFService> login(string sUserID, string password);

定义相同

 public List<ParkingLotRestWCFService> login(string sUserID, string password)
   {
        ParkingLotRestWCFService login = null;
        List<ParkingLotRestWCFService> arrList = new List<ParkingLotRestWCFService>();
        string json = "";
      try
        {
            string _connectionstring = "Data Source=LM;Initial Catalog=parkinglotdb;Integrated Security=true";
            string _sql1 = "SELECT * FROM [LoginDetails] WHERE EmpID = " + sUserID + " AND Pwd = '" + password + "'";
            SqlConnection _connection = new SqlConnection(_connectionstring);
            SqlCommand _command = new SqlCommand(_sql1, _connection);
            _connection.Open();
            SqlDataReader reader = _command.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Close();
                string _sql2 = "EXEC [dbo].[loginVerify]";
                SqlCommand _command2 = new SqlCommand(_sql2, _connection);
                SqlDataReader reader2 = _command2.ExecuteReader();
                reader2.Read();

                login = new ParkingLotRestWCFService();
                login.status = "Valid";
                login.empID = reader2["EmpID"].ToString();
                login.empName = reader2["Name"].ToString();
                login.secFlag = reader2["SecFlag"].ToString();

                arrList.Add(login);
                reader2.Close();

                //JavaScriptSerializer ser = new JavaScriptSerializer();
                //json = ser.Serialize(arrList.ToArray());
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
                WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
               WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET");
               WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept"); 

            }
            else
            {
                reader.Close();
                login.status = "Invalid";
                login.empID = string.Empty;
                login.empName = string.Empty;
                login.secFlag = string.Empty;

                arrList.Add(login);
            }
            _connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;

        }

        return arrList;
    }

Jquery Ajax 代码:

 $('#signIn').on('click',function(){
        var userId=$('#userId').val();
        var pass=$('#password').val();
        var sUrl='http://localhost/ParkingLotRestWCFService.svc/login/'+userId+'/'+pass;
        $.ajax({
                url: sUrl,
            type:"GET",
            contentType: 'application/json; charset=utf-8',
            dataType:"jsonp",
                            jsonp:'jsonp',
                            crossDomain:true,
            success: function (data, textStatus, jqXHR) {
                           //process the json response
               alert("success:"+retData);
            },
            error:function (result, sts, err) {
            alert("inside error block");
                alert(err+":"+sts+":"+result);
            },
            complete: function (jqXHR, textStatus) {
                alert("completed");
            }

        });
    });

所以问题是,每当我进行 ajax 调用时,控件都会进入错误块,即使我可以在 Firebug 控制台的 Net 选项卡下的 response 部分中看到实际的 json 数据。错误消息错误块内部将被警告为 Error: jQuery111108245764932074613_1403187289975 was not called:parsererror:[object Object]

我在 firebug 控制台收到此错误消息

      SyntaxError: missing ; before statement
          {"loginResult":[{"empID":"300","empName":"User1","loginTime":null,"logo
           -------------^

这是从我的 WCF 服务返回的 json 响应

JSON 响应:
{"loginResult":[{"empID":"300","empName":"User1","loginTime":null,"logoutTime":null,"secFlag":"A","slotNo":null,"status":"Valid","vechicleNo":null,"vechicleType":null}]}

注意:

  1. 如果我直接从浏览器点击传递给 jquery 的 url,它会返回我的 json 数据而没有任何错误,但同样不适用于 jquery ajax 调用
  2. 我什至在http://jsonlint.com/ 验证了json 响应,它是有效的json

任何快速帮助将不胜感激 :)

【问题讨论】:

  • 来自您服务器的响应似乎不是 JSONP。JSONP 实际上是 javascript,应该如下所示:callback({yourjsonhere})
  • 你的服务不支持jsonp调用,尝试只使用json
  • @sakir:实际上我已经在 WCF 服务端启用了 cors 但仍然遇到问题,请告诉我如何启用 cors(如果尚未启用)以及如何在回调函数中返回 json 数据以便我的 ajax 调用可以正确解析它
  • 这里是你如何启用[这里是你如何启用][1] [1]:stackoverflow.com/questions/8219579/…

标签: jquery ajax json wcf restful-url


【解决方案1】:

web.config

<configuration>
  <system.web>
    <compilation debug="true" targetframework="4.0">
    <authentication mode="None">
  </authentication></compilation></system.web>
  <system.webserver>
    <modules runallmanagedmodulesforallrequests="true">
  </modules></system.webserver>
  <system.servicemodel>
    <servicehostingenvironment **aspnetcompatibilityenabled**="true">
    <standardendpoints>
      <webscriptendpoint>
        <standardendpoint **crossdomainscriptaccessenabled**="true" name="">
      </standardendpoint></webscriptendpoint>
    </standardendpoints>
  </servicehostingenvironment></system.servicemodel>
</configuration>

【讨论】:

  • 谢谢你,但它不起作用兄弟,jquery ajax 的行为和以前一样。还有其他解决方案吗?
  • 与我在问题中提到的萤火虫中的语法错误相同,它还输入了带有"Error: jQuery1111010482331053579053_1403247295078 was not called:parsererror:[object Object]" 错误消息的 ajax 调用的错误块。在添加您的解决方案之前,这也是相同的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
相关资源
最近更新 更多