簡體   English   中英

Ajax調用無法使用WCF靜態服務

[英]Ajax call failing to consume the WCF restful service

我有一個WCF restful服務,它將登錄方法公開給外部,定義如下,它僅使用DB(登錄表)驗證給定的用戶憑據並以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數據。錯誤塊內的錯誤消息也將被警告為錯誤:jQuery111108245764932074613_1403187289975沒有被調用:parsererror:[object Object]

我在螢火蟲控制台上收到此錯誤消息

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

這是json響應,從我的WCF服務返回

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

任何快速幫助將不勝感激的家伙:)

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM