我不确定为什么这不起作用
js - 它会提醒宽度,将其发送给控制器,但不会提示“完成”。
网络 - >预览(检查元素Chrome)
content: "<ul><li>50</li></ul>"
status: "ok"
$("#submit").click(function (e) {
e.preventDefault();
var width = $('#value').val();
$.ajax({
url: "http://domain.com/index.php/welcome/get_items",
data: {
width: width
}
}).done(function(data) {
$('div#cont').text(data);
}).fail(function() {
alert('Failed!')
});
});
控制器
public function get_items()
{
$this->load->model('home_model');
$this->load->library('form_validation');
$this->form_validation->set_rules('width', 'Width', 'trim|required|xss_clean');
$width = $_GET['width'];
var_dump($width);
$one_exp = $this->home_model->one_exp($width);
var_dump($one_exp);
if($one_exp != false){
//$html = '<ul>';
foreach($one_exp as $exp) {
$html = $exp->width;
}
//$html .= '</ul>';
$result = array('status' => 'ok', 'content' => $html);
//header('Content-type: application/json');
echo json_encode($result);
exit();
}else{
$result = array('status' => 'no', 'content' => 'nothing here');
//header('Content-type: application/json');
echo json_encode($result);
exit();
}
}
home_model
function one_exp($width) {
$query_str = "SELECT * FROM files WHERE width=?";
$query = $this->db->query($query_str, array($width));
if($query->num_rows() > 0) {
foreach($query->result() as $item) {
$data[] = $item;
}
return $data;
} else {
return false;
}
}
答案 0 :(得分:2)
删除echo
public function get_items()
{
$this->load->model('home_model');
$width = $this->input->post('width');
$one_exp = $this->home_model->one_exp();
if ($one_exp != NULL)
{
$html = '<ul>'; //remove echo
foreach($one_exp as $exp)
{
$html .= '<li>';
$html .= $exp->width;
$html .= '</li>';
}
$html .= '</ul>';
$result = array('status' => 'ok', 'content' => $html);
echo json_encode($result);
exit();
}
else
{
$result = array('status' => 'no', 'content' => 'nothing here');
echo json_encode($result);
exit();
}
}
答案 1 :(得分:1)
您使用的是哪个版本的jQuery?如果您使用的是更高版本,则语法可能无法正常工作。您可能还遇到Access-Control-Allow-Origin失败。
也就是说,尝试使用jQuery 1.9.X或更高版本,并使用更详细的$.ajax
方法:
$(document).ready(function () {
$("#click").click(function () {
var width = $('#width').val();
alert(width);
$.ajax({
url: "http://mywebsite.com/index.php/welcome/get_items",
data: {
width: width
}
}).done(function (data) {
alert(data);
}).fail(function() {
alert('Failed!')
});
});
});
在此处查看此操作,并且控制台日志中还显示了跨源失败:http://jsfiddle.net/remus/LcTe4/
不要忘记删除Ashok答案中指出的echo
,并且最好添加json内容类型:
header('Content-type: application/json');
echo json_encode($result);