我正在构建一个codeigniter / php Web应用程序.
我正在尝试在加载视图时将JSON对象从控制器传递到视图,以使JavaScript可以访问它.
JSON如下所示:
{
"event": {
"id": "1",
"name": "Some name",
"description": "Some description",
"address": "1 Main st."
},
"members": {
"others": [
{
"id": "26",
"name": "Brad Black"
},
{
"id": "27",
"name": "Bill Blue"
}
],
"current": {
"id": "1",
"name": "Jill White"
}
}
}
控制器代码如下所示:
public function index()
{
$some_data = $this->Some_model->get_some_data();
$some_data = json_encode($some_data);
$data = array (
'some_data' => $some_data
);
$this->load->view('some_view',$data);
}
视图(some_view)代码如下所示:
<script src="path/to/scripts/some_script.js" type="text/javascript"></script>
<script type="text/javascript">
some_data = "<?php echo $some_data?>";
</script>
<div class="main">
</div>
javascript(some_script)代码如下所示:
var some_data;
$(document).ready(function(){
some_data = $.parseJSON(some_data);
});
面临的挑战是,由于JSON对象是作为字符串发送的(在json_encode之后),因此它具有诸如{和引号的字符,其中的一部分,当我将其分配给var(some_data =“” ;).我也尝试过使用,但效果不佳.
我尝试做一堆不起作用的事情,为了取得进展,我暂时最终替换了控制器中的“
$data [‘some_data’] = str_replace(‘“’,”“”,$some_data);
public function index()
{
$some_data = $this->Some_model->get_some_data();
$some_data = json_encode($some_data);
$data = array (
'some_data' => str_replace('"', """, $some_data);
);
$this->load->view('some_view',$data);
}
并替换javascript中的“返回”
some_data = some_data.replace(/“ / g,’”’);
var some_data;
$(document).ready(function(){
event_data = event_data.replace(/"/g, '"');
some_data = $.parseJSON(some_data);
});
这有点丑陋,我正在寻找更好的解决方案.
任何指针将不胜感激.
更新!
问题解决了,好像多余的引号打断了事情.
解决方案与mohan.gade的答案一致:
控制器:
public function index()
{
$some_data = $this->Some_model->get_some_data();
$some_data = json_encode($some_data);
$data = array (
'some_data' => $some_data;
);
$this->load->view('some_view',$data);
}
视图:
some_data = <?php echo $some_data?>;
</script>
解决方法:
您的JSON值未传递给视图,请尝试更正以下代码.
public function index()
{
$some_data = $this->Some_model->get_some_data();
$some_data = json_encode($some_data);
$data = array (
'some_data' => $some_data
);
$this->load->view('some_view',$data);
}
//in view file
<script type="text/javascript">
var jsonData = <?php echo $some_data; ?>
</script>