功能范围与Javascript原型

时间:2016-10-16 22:18:27

标签: javascript json prototype

我一直在练习使用原型,试图让更大的项目更容易让我遵循。我专注于分离流程,但我似乎遇到了我认为是范围问题。将信息发送到PHPMYSQLJSON的{​​{1}}页面时,我收到错误消息,指出函数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 个答案:

答案 0 :(得分: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));