2017-12-18 11 views
0

나는 이것에 대해 좀 새로운 것이고, 정확히 어떻게 AJAX 호출을 통해 웹 메소드로 리턴되어야하는지, 그리고 어떻게 처리해야하는지에 대해 두뇌를 감싸는 데 어려움을 겪고있다. 간단한 로그인 화면을 만들려고합니다.웹 방식의 AJAX 로그인 화면?

HTML :

  <asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true"></asp:ScriptManager> 

      <input type="text" placeholder="username" id="username" /> 
      <input type="password" placeholder="password" id="password" /> 
      <button id="loginbutton" onclick="UserLogin()" type="submit">login</button> 

자바 스크립트 :

function UserLogin() { 

     var postData = JSON.stringify({ 
      "username": $("#username").val(), 
      "password": $("#password").val() 
     }); 
     alert(postData); 
     $.ajax({ 
      type: "POST", 
      url: "login.aspx/AuthenticateUser", 
      data: postData, 
      contentType: "application/json; charset=utf-8", 
      success: callbackfunction, 
      error: function (msg) { alert(msg); } 
     }); 


    } 

    function callbackfunction(result) { 
     alert('callback'); 
     if (result.d) { 
      alert('success'); 
     } 
    } 

웹 방법 :

가 여기에 내가 가진 무엇

 <WebMethod()> 
Public Shared Function AuthenticateUser(sID As String, sPassword As String) As Boolean 


    Dim db As New ProjectDatabase 
    Dim ed As New EncryptDecrypt 

    Dim sSQL As String = "SELECT [USER_ID] FROM [USERS] WHERE [USER_ID] = '" & sID & "' AND [PASSWORD] = '" & ed.Encrypt(sPassword) & "'" 

    'will return the result of the query, either a user id or nothing 
    Dim sRtn As String = db.GetSQLData(sSQL, db._cnnSQL) 

    If sRtn = "" Then 
     Return False 
    Else 
     Return True 
    End If 

End Function 

을 그래서 바로 그것을 이해한다면, 나는 웹 메소드에서 true 또는 false를 반환 할 수 있어야하지만, 어떤 이유로 (중단 점에 도달하지 않고) AJAX의 양쪽 끝이 메시지 상자를 던져야한다. 그러나 그것도 발생하지 않습니다.

나는이 질문을 알고 있으며 여러 기사를 읽었지만 여전히 올바르게 이해할 수없는 것 같습니다.

어떤 조언을 주셔서 감사합니다.

+0

로그인 엔드 포인트에 관해서는 응답 내용이 가장 큰 문제가 아닐 것이라고 제안합니다. 응답 코드는입니다. 단순히 200 (OK) 또는 401 (Unauthorized)을 반환하면 클라이언트가 사용자가 로그인 할 수있는 위치를 정확히 알 수 있습니다. – Taplar

+0

대신 false를 반환합니다. '새 WebFaultException (Of ErrMessage) (str, HttpStatusCode.BadRequest)'오류가 발생하면 아약스의 오류 부분으로 이동해야합니다. – MB34

+0

'AJAX'와'WebMethod'에서 같은 변수 이름을 사용하십시오. 그것은'username' 또는'sID'입니다. –

답변

0

로그인 버튼은 전체 포스트 백을 시작하게하는 type="submit"이므로 거의 확실하게이 동작으로 인해 ajax 요청이 발생하지 않습니다. type="button"

0

변경은이 시도 -

HTML -

<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true"></asp:ScriptManager> 

     <input type="text" placeholder="username" id="username" /> 
     <input type="password" placeholder="password" id="password" /> 
     <button id="loginbutton" onclick="UserLogin()" type="submit">login</button> 

JAVASCRIPT -

function UserLogin() { 

    var postData = JSON.stringify({ 
     "username": $("#username").val(), 
     "password": $("#password").val() 
    }); 
    alert(postData); 
    $.ajax({ 
     type: "POST", 
     url: "login.aspx/AuthenticateUser", 
     data: "{'data': '" + postData+ "'}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: callbackfunction(result), 
     error: function (msg) { debugger;alert(msg); } 
    }); 


} 

function callbackfunction(result) { 
    debugger; 
    alert('callback'); 
    if (result.d) { 
     alert('success'); 
    } 
} 

웹 방법 -

using NewtonSoft.Json; 

<WebMethod()> 
Public Shared Function AuthenticateUser(data As String) As Boolean 


Dim db As New ProjectDatabase 
Dim ed As New EncryptDecrypt 
Dim dt As New Datatable = JsonConvert.DeserializeObject<DataTable>(data); 

Dim sSQL As String = "SELECT [USER_ID] FROM [USERS] WHERE [USER_ID] = '" & dt.Rows(0).Item("username") & "' AND [PASSWORD] = '" & ed.Encrypt(dt.Rows(0).Item("password")) & "'" 

'will return the result of the query, either a user id or nothing 
Dim sRtn As String = db.GetSQLData(sSQL, db._cnnSQL) 

If sRtn = "" Then 
    Return False 
Else 
    Return True 
End If 

End Function 

이것은 데이터를 가져와 브라우저에서 디버깅하게합니다.