2016-10-16 2 views
0

큰 프로젝트를 더 쉽게 수행 할 수 있도록 프로토 타입을 사용하는 연습을 해왔습니다. 나는 분리 과정에 초점을 맞추고 있지만, 나는 범위 문제라고 생각하는 것에 빠져있는 것 같다. MYSQL에서 JSON으로 PHP 페이지로 정보를 보낼 때 createAccountConfirm 함수가 존재하지 않는다는 오류가 발생합니다. JSON 요청은 함수를 실행하기 위해 응답을 기다리고 있지만 함수는 액세스 할 수없는 것처럼 보입니다. 누군가를 바라는 것은 내가 잘못 가고있는 곳을 밝힐 수있어서이 프로젝트로 다시 돌아올 수 있습니다. 미리 감사드립니다!자바 스크립트 프로토 타이핑 기능 범위

클라이언트 측 코드 :

_wolc.prototype.account = { 

createAccount: function() { 

    var subArr = []; 

    subArr[0] = document.getElementById("newName").value.toString(); 
    subArr[1] = document.getElementById("newPassword_1").value.toString(); 
    subArr[2] = document.getElementById("newPassword_2").value.toString(); 
    subArr[3] = document.getElementById("newEmail").value.toString(); 

    if (subArr[1] === subArr[2]) { 

     // Pass the values to the server side function checkUser for validation; return to createAccountConfirm() 
     if (window.XMLHttpRequest) { 
      // code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp = new XMLHttpRequest(); 
     } else { 
      // code for IE6, IE5 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     xmlhttp.onreadystatechange = function() { 
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 

       this.createAccountConfirm(JSON.parse(xmlhttp.responseText)); 

      } 
     }; 

     xmlhttp.open("GET","create_account.php?un="+subArr[0]+ 
              "&pw="+subArr[1]+ 
              "&em="+subArr[3] 
              ,true); 
     xmlhttp.send(); 

    } else { 

     console.log("Passwords don't match"); 

    } 

}, 

createAccountConfirm: function (response) { 

    console.log(response); 

} 

}; 

서버 코드 :

<?php 

include 'connection_settings.php'; 

$usr = $_GET['un']; 
$psw = $_GET['pw']; 
$eml = $_GET['em']; 
$tms = date ("Y-m-d H:i:s"); 

$psw = md5($psw); 

$con = mysqli_connect($localhost,$username,$password,$database); 

// Check connection 
if (!$con) { 

    die('Could not connect: ' . mysqli_error($con)); 

} 

mysqli_select_db($con,$database); 

$sql="INSERT INTO user_accounts (Account_Name, Join_Date, Last_Date,Account_Password,Account_Email) 
VALUES ('".$usr."', '".$tms."', '".$tms."','".$psw."','".$eml."')"; 

if ($con->query($sql) === TRUE) { 

    echo json_encode("New record created successfully"); 

} else { 

    echo json_encode("Error: New record failed to create"); 

} 

mysqli_close($con); 

?> 

답변

1

이 자세한 설명은 How to access the correct `this` context inside a callback?을 볼 수 있지만, 기본적으로 this 중첩 (콜백) 함수에서이 _wolc.prototype.account 개체를 참조하지 않습니다 . 콜백에서 사용하려면 참조를 저장해야합니다.

_wolc.prototype.account = {  
    createAccount: function() { 
    // [...] 

    // save the reference to `this` to use in the callback: 
    var self = this; 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 

     // use `self` instead of `this` in the callback: 
     self.createAccountConfirm(JSON.parse(xmlhttp.responseText)); 
+0

생성 함수에 'wolc.account'객체가 전달되어 작동합니다. 나는 전에 시도 했었지만 그 물건을 잘못 넣었어야합니다. 감사! 나는 이것에 관해 읽을 것이지만, 그것은 문제를 해결했다. 물론 그것을 전달할 필요는 없지만 JSON 부분을 호출하기 전에 'self'를 선언하는 변수를 작성하십시오. – xxSithRagexx