如何在laravel中调用ajax文件

时间:2018-05-21 10:57:14

标签: php html sql ajax laravel

我有一个保存为ajax.php的ajax文件,其中包含以下代码:



<?php
// Start the session
session_start();

$con=mysqli_connect("localhost","root","","quiz"); // change here to your data
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Check the number of all questions, if next_id is more than last question, back to first or whatever you want;
$response=mysqli_query($con,"select * from questions");
$number_of_all_questions = mysqli_num_rows($response);

if($_POST['next_id'] == 0){
	// reset to default
	$_SESSION["correct_score"] = 0;
	$_SESSION["not_correct_score"] = 0;
}


if($number_of_all_questions <= $_POST['next_id']){
	// Quiz finished, show results
    echo"<div>
	<h2>Results:</h2>
	<p>Correct answers: {$_SESSION['correct_score']}</p>
	<p>Wrong answers: {$_SESSION['not_correct_score']}</p>

	</div>";



}else{

	// query next question
	$response=mysqli_query($con,"select * from questions WHERE id =(select min(id) from questions where id > {$_POST['next_id']})");
	?>

	<?php while($result=mysqli_fetch_array($response,MYSQLI_ASSOC)){ ?>

		<div id="question_<?= $result['id'] ?>" class='question' data-next-question="<?= $_POST['next_id'] ?>"> <!--check the class for plurals if error occurs-->
			<h2><?= $result['id'].".".$result['question_name'] ?></h2>
			<div class='align'>
				<input type="radio" value="1" id='radio1' name='1'>
				<label id='ans1' for='radio1'><?= $result['answer1'] ?></label>
				<br/>
				<input type="radio" value="2" id='radio2' name='2'>
				<label id='ans2' for='radio2'><?= $result['answer2'] ?></label>
				<br/>
				<input type="radio" value="3" id='radio3' name='3'>
				<label id='ans3' for='radio3'><?= $result['answer3'] ?></label>
				<br/>
				<input type="radio" value="4" id='radio4' name='4'>
				<label id='ans4' for='radio4'><?= $result['answer4'] ?></label>
			</div>
			<br/>
			<?php /*<input type="button" data-next-question="<?= $_POST['next_id'] ?>" id='next' value='Next!' name='question' class='butt'/> */?>
		</div>
	<?php }?>
<?php }?>
<?php mysqli_close($con); ?>
&#13;
&#13;
&#13;

ajax文件包含从我的数据库中获取问题的代码&#34;测验&#34;。我使用PHP和HTML做到了这一点并且运行正常。现在我把它转移到laravel。问题是,在视图刀片中只显示普通的html。问题没有显示在刀片​​中。如何在我的视图刀片中调用此ajax文件

1 个答案:

答案 0 :(得分:2)

你应该在控制器中移动你的php代码并通过路由访问它,但是你应该使用雄辩的ORM从数据库中获取数据,只需为你的刀片视图准备变量并显示它们。

here is a tutorial

laravel docs is another choice