我试图通过 JavaScript 使用 this.id 将 View 加载到我的 div #teste 中,但没有成功。我的函数出了什么问题?
下面的 JavaScript 函数
<script type="text/javascript">
var baseurl = '<?php site_url(); ?>'; //raiz do website
function navbutton(id) {
$.ajax({
type: 'GET',
url: baseurl+'main/'+id,
dataType: 'html',
success: function(html) {
$('#teste').html(html);
}
});
}
HTML 按钮
<li><a href="javascript:void(0)" id="contato" onclick="navbutton(this.id)">Contato</a></li>
我的主 Controller (调用所有其他 View 的一个函数)
class Main extends CI_Controller {
var $_data = array();
public function index()
{
if (!$this->uri->segment(1) && !$this->uri->segment(2)) {
$view = 'inicio';
}
if ($this->uri->segment(1) && !$this->uri->segment(2)) {
$view = $this->uri->segment(1, 'inicio');
}
if ($this->uri->segment(1) && $this->uri->segment(2)) {
$view = $this->uri->segment(1, 'inicio') . '/' . $this->uri->segment(2, '');
}
if (!file_exists(APPPATH . 'views/' . $view . EXT)) {
$view = "404";
header("HTTP/1.0 404 Not Found");
}
$this->load->view('templates/header');
$this->load->view($view, $this->_data);
$this->load->view('templates/footer');
}
最佳答案
避免出现“Uncaught ReferenceError: navbutton is not defined”错误 使用 javascript 附加点击事件函数:
var baseurl = '<?php site_url(); ?>'; //raiz do website
function navbutton(id) {
$.ajax({
type: 'GET',
url: baseurl+'main/'+id,
dataType: 'html',
success: function(html) {
$('#teste').html(html);
},
error:function(v1,v2,v3){
alert('Something went wrong'); }
});
}
$("#contato").on('click',function(event){
event.preventDefault();
navbutton(this.id);
});
在 HTML 上使用
<li><a href="#" id="contato">Contato</a></li>
JSFIDLE test - 在此示例中,ajax 请求将收到错误 404,因为 url 未正确定义,但您的代码必须有效。
提示确保所有代码都在正确的位置,在浏览器中加载后查看页面的源代码(CTRL+U)
关于javascript - 使用 javascript 函数加载 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30008398/