我试图在CI中对ajax进行一些简单的练习。 但没有回应......我试图设置断点警报(“aa”)并且失败了; 但警报是在ajax代码之前或之后进行的。 有人可以帮忙解决吗?非常感谢。 这是代码
View
<!DOCTYPE html>
<html>
<head>
<!-- ajax example-->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function AJAX_call() {
a_val = $('[name="a"]').val();
b_val = $('[name="b"]').val();
AJAX_url = '<?php echo base_url()."index.php/ajax_example/AJAX_calc";?>';
$.ajax({
type: "POST",
url : AJAX_url,
data: {a : a_val, b : b_val },
dataType: "json",
success: function(data2) {alert("aa");$('#result').html(data2.result); }
});
}</script>
</head>
<body>
<form onsubmit="AJAX_call();">
<label>Enter A</label>
<input type="text" name="a" />
<label>Enter B</label>
<input type="text" name="b" />
Result:
<div id='result'>The Result Will Be Shown Here</div>
<input type="submit" value="Calculate" />
</form>
</body>
</html>
控制器
<?php
class Ajax_example extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index()
{
$this->load->helper('url');
$view_params="";
$this->load->view('ajax_view',$view_params);
}
function AJAX_calc() {
if (!$this->input->is_AJAX_request()) exit ('none AJAX calls rejected!');
$a = $this->input->post('a');
$b = $this->input->post('b');
$result = (int) $a * (int) $b;
$data = array('result'=> $result);
echo json_encode($data);
return;
}
}
答案 0 :(得分:0)
您的代码遇到2个问题:
onsubmit
提交整个页面并丢失你的ajax结果你的js功能将是:
function AJAX_call() {
a_val = $('#a').val();
b_val = $('#b').val();
AJAX_url = '<?php echo base_url()."remote/AJAX_calc";?>';
$.ajax({
type: "POST",
url : AJAX_url,
data: {a : a_val, b : b_val },
dataType: "json",
success: function(data2) {alert("aa");$('#result').html(data2.result); }
});
}
,你的html表单将是:
<form >
<label>Enter A</label>
<input type="text" id="a" value="" />
<label>Enter B</label>
<input type="text" id="b" value="" />
Result:
<div id='result'>The Result Will Be Shown Here</div>
<button type="button" onclick="AJAX_call();">Calculate</button>
</form>
答案 1 :(得分:0)
将视图文件ajax_view
替换为以下文件:
<!DOCTYPE html>
<html>
<head>
<!-- ajax example-->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function AJAX_call(event) {
a_val = $('[name="a"]').val();
b_val = $('[name="b"]').val();
AJAX_url = '<?php echo base_url()."index.php/ajax_example/AJAX_calc";?>';
$.ajax({
type: "POST",
url : AJAX_url,
data: {a : a_val, b : b_val },
dataType: "json",
success: function(data2) {alert("aa");$('#result').html(data2.result); }
});
event.preventDefault();
}</script>
</head>
<body>
<form onsubmit="AJAX_call(event);">
<label>Enter A</label>
<input type="text" name="a" />
<label>Enter B</label>
<input type="text" name="b" />
Result:
<div id='result'>The Result Will Be Shown Here</div>
<input type="submit" value="Calculate" />
</form>
</body>
</html>
event.preventDefault()
函数中使用了AJAX_call
方法。如果调用此方法,则不会触发事件的默认操作(重新加载页面)。