创建函数构造函数会导致在没有实例的情况下在运行时编译时出现未捕获的类型错误

时间:2017-02-13 16:47:38

标签: javascript jquery json ajax get

所以我的网站的目标是成为一个简单的问答游戏。 它使用ajax获取一组json问题,然后对于数组中的每个问题,它显示实际问题并创建具有各种选项的按钮,这些选项也存储在问题对象中。我似乎无法让这个工作。 单击按钮时,它应转到json数组中的下一个问题对象。我正在使用Quiz对象来跟踪它。 现在我在创建对象时遇到错误,而不是在我将它们作为实例启动时。

当我尝试通过getQuestionhandler函数返回它来创建一个新的QuestionHandler对象时,它在Chrome开发工具中将此视为错误:

/*function GetJsonQuestions(){
   var url = "https://api.myjson.com/bins/10t76x";
    $.ajax({
    url: url,
    data: "json",
    success: function(){
        console.log("get is successfull");
    },
    dataType: dataType
});
}*/


var urlJson = "https://api.myjson.com/bins/10t76x";

var QuestionHandler = function(question, options, answer) {

  this.question = question;
  this.options = options;
  this.answer = answer;

  this.isCorrect = function(guess) {

    if (this.answer === guess) {
      return true;
    }

  };

};

var PointsHandler = function() {

  this.points = 0;

  this.addPoint = function() {
    this.points++;
  };


};

var getAllData = function() {
  var allData = null;

  $.ajax({
    url: urlJson,
    type: 'GET',
    dataType: 'json', // added data type
    success: function(res) {
      console.log(res);
      allData = res.questions;
    },
    error: function(err) {
      console.log("error: " + err);


    }
  });

  return allData;
};

var QuizGame = function() {
  this.index = 0;
  this.allJsonData = getAllData();
  this.pointHandler = getPointsHandler();
  this.questionHandler = getQuestionHandler();
  this.gameResult = getResult();
  this.getPoints = function() {
    return this.pointHandler.points;
  };


  this.nextQuestion = function(quess) {
    index++;
    var correct = questionHandler.isCorrect(guess);
    if (correct) {
      pointsHandler.addPoints();
    }

  };

  function getPointsHandler() {
    var handler = new PointsHandler();
    return handler;
  }


  function getResult() {
    return "You answered " + this.points + " correct out of " + this.index + " questions";
  }

  function getQuestionHandler() {
    var qHandler = new QuestionHandler(this.allJsonData[this.index].question, this.allJsonData[this.index].options, this.allJsonData[this.index].answer);
    return qHandler; //this function seems to be giving the error
  }
};

var myQuiz = new QuizGame();


console.log(myQuiz.allJsonData);

$("#question").text("Question nr " + myQuiz.index + " : " + myQuiz.questionHandler.question);

$.each(myQuiz.questionHandler.options, function(i, val) {

  $("#options").append("<button>" + val + "</button>");


});

$("button").click(function(e) {


  if (myQuiz.index <= myQuiz.allJsonData.length) {

    myQuiz.nextQuestion(e.target.nodeValue);


  }

});

这是我没有css样式的整个代码:

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="quizStyle.css">


  <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous">
  </script>


  <script src="Handlers.js"></script>
  <title>Quiz time</title>
</head>

<body>
  <h1></h1>

  <div id="quizDiv">
    <p>Question:</p>
    <h2 id="question">Test</h2>
    <p>Answers:</p>
    <div id="options">

    </div>
  </div>

  <div id="resultDiv">
    <p id="yourResult">You got x out x right!</p>
  </div>

  <script>
  </script>
</body>

</html>
savez

导致错误的原因是什么?如何解决?

2 个答案:

答案 0 :(得分:0)

这是代码的功能性和固定示例。它没有移动到下一个问题,因为它似乎没有编程它这样做。

&#13;
&#13;
var urlJson = "https://api.myjson.com/bins/10t76x";

var QuestionHandler = function(question, options, answer) {

  this.question = question;
  this.options = options;
  this.answer = answer;

  this.isCorrect = function(guess) {
		rtn = false;
    if(this.answer === guess) rtn = true;
		return rtn;
  };

};

var PointsHandler = function() {

  this.points = 0;

  this.addPoint = function() {
    this.points++;
  };


};

var getAllData = function() {
  var allData = null;

  $.ajax({
    url: urlJson,
    type: 'GET',
		async: false,
    dataType: 'json',
    success: function(res) {
      allData = res.questions;
    },
    error: function(err) {
      console.log("error: " + err);
    }
  });
  return allData;
};

var QuizGame = function() {

  function getResult() {
    return "You answered " + this.points + " correct out of " + this.index + " questions";
  }
	
  this.index = 0;
  this.allJsonData = getAllData();
  this.pointsHandler = new PointsHandler();
  this.questionHandler = new QuestionHandler(this.allJsonData[this.index].question, this.allJsonData[this.index].options, this.allJsonData[this.index].answer);
  this.gameResult = getResult();
  this.getPoints = function() {
    return this.pointHandler.points;
  };


  this.nextQuestion = function(guess) {
		
		this.index++;
		
		var correct = this.questionHandler.isCorrect( guess );
    
		console.log( correct );

		if (correct) {
      this.pointsHandler.addPoint();
    }
		
		console.log(this);
		
  };
	
};

var myQuiz = new QuizGame();

$("#question").text("Question " + (myQuiz.index + 1) + ": " + myQuiz.questionHandler.question);

$.each(myQuiz.questionHandler.options, function(i, val) {

  $("#options").append("<button>" + val + "</button>");


});

$("button").click(function(e) {
  if (myQuiz.index <= myQuiz.allJsonData.length) {
    myQuiz.nextQuestion(this.innerText.trim());
  }
});
&#13;
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="quizStyle.css">


  <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous">
  </script>


  <script src="Handlers.js"></script>
  <title>Quiz time</title>
</head>

<body>
  <h1></h1>

  <div id="quizDiv">
    <p>Question:</p>
    <h2 id="question">Test</h2>
    <p>Answers:</p>
    <div id="options">

    </div>
  </div>

  <div id="resultDiv">
    <p id="yourResult">You got x out x right!</p>
  </div>

  <script>
  </script>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的代码中存在多个错误/错误。

主要问题:由于allData(异步通话)

,您无法从getAllData返回AJAX

我重构了所有这些,这是一个有效的例子。

&#13;
&#13;
var urlJson = "https://api.myjson.com/bins/10t76x";

var QuestionHandler = function(question, options, answer) {
  var self = this;
  self.question = question;
  self.options = options;
  self.answer = answer;
  self.isCorrect = function(guess) { return self.answer === guess; }
};

var PointsHandler = function() {
  var self = this;
  self.points = 0;
  self.addPoints = function() { self.points++; }
};

var QuizGame = function(data) {
  var self = this;
  self.index = 0;
  self.allJsonData = data;
  self.pointsHandler = getPointsHandler();
  self.questionHandlers = getQuestionHandlers();
  self.gameResult = getResult;
  self.getPoints = function() {
    return self.pointsHandler.points;
  };

  self.nextQuestion = function(guess) {
    var correct = self.questionHandlers[self.index].isCorrect(guess);
    if (correct) {
      self.pointsHandler.addPoints();
    }
    self.index++;
    if (self.index < self.allJsonData.length) {
	update(self);
    } else {
        done(self);
    }
  };

  function getPointsHandler() { return  new PointsHandler(); }

  function getResult() {
    return "You answered " + self.pointsHandler.points + " correct out of " + self.index + " questions";
  }

  function getQuestionHandlers() {
    return self.allJsonData.map(function(d) { return new QuestionHandler(d.question, d.options, d.answer); });
  }
};


function getAllData() {
  $.ajax({
    url: urlJson,
    type: 'GET',
    dataType: 'json', // added data type
    success: onSuccess,
    error: function(err) { console.log("error: " + err); }
  });
};

function onSuccess(res) {
  var myQuiz = new QuizGame(res.questions);
  update(myQuiz);
}

function update(myQuiz) {
  $("#question").text("Question nr " + (myQuiz.index + 1) + " : " + myQuiz.questionHandlers[myQuiz.index].question);
  $("#options").empty();
  $.each(myQuiz.questionHandlers[myQuiz.index].options, function(i, val) {
    $("#options").append("<button>" + val + "</button>");
  });

  $("button").click(function(e) { myQuiz.nextQuestion(e.target.innerText); });
  $('#yourResult').text(myQuiz.gameResult());

}

function done(myQuiz) {
  $("#quizDiv").text('Completed.');
  $('#yourResult').text(myQuiz.gameResult());
}

getAllData();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quizDiv">
  <p>Question:</p>
  <h2 id="question">Test</h2>
  <p>Answers:</p>
  <div id="options"></div>
</div>
<div id="resultDiv">
  <p id="yourResult">You got x out x right!</p>
</div>
&#13;
&#13;
&#13;