php - 我如何在 laravel 中调用 ajax 文件
问题描述
我有一个保存为 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); ?>
ajax 文件包含从我的数据库“测验”中获取问题的代码。我使用 PHP 和 HTML 做到了这一点,并且效果很好。现在我将它转移到laravel。问题是,只有普通的 html 显示在视图刀片中。问题未显示在刀片中。我如何在我的视图刀片中调用这个 ajax 文件
解决方案
你应该在你的控制器中移动你的 php 代码并通过路由访问它,但是你应该使用 eloquent ORM 从你的数据库中获取数据,只为你的刀片视图准备变量并显示它们。
推荐阅读
- css - 以闪亮的方式改变下拉菜单的颜色
- javascript - Angular - 取决于变量值的条件名称
- javascript - 如何处理无法访问的 XMLHttpRequest 端点
- angular - ActivatedRoute 未定义自定义按钮单击
- c# - 获取给定日期c#的开始周的日期
- swift - 检测 UITextField 中的提及不起作用
- html - html css 定位前景
- ruby-on-rails - 在 rails-postgres-rgeo 项目中按 lat / lon 查找记录
- video - 通过 Gstreamer 流式传输视频
- angular - TypeScript - 用它的值初始化枚举变量