Ajax调用无法使用WCF restful服务

时间:2014-06-19 14:29:58

标签: jquery ajax json wcf restful-url

我有一个WCF restful服务,它向外界公开登录方法定义如下,它只是用DB(登录表)和&amp ;;验证给定的用户凭证。以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调用,控件都会进入错误块,即使我可以在json标签下的response部分中看到实际的Net数据Firebug console.错误块内的错误消息将被警告为错误:未调用jQuery111108245764932074613_1403187289975: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
  3. 任何快速帮助将非常感谢大家:)

1 个答案:

答案 0 :(得分:0)

的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>