javascript Codeigniter - 如何将 JSON 作为参数传递给视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13715463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:35:05  来源:igfitidea点击:

Codeigniter - how to pass JSON as a parameter to the view

phpjavascriptjsoncodeigniterview

提问by user898836

I'm building a codeigniter/php web application. I'm trying to pass a JSON object from the controller to the view when the view is loaded, in a way that it will be accessible to the javascript.

我正在构建一个 codeigniter/php web 应用程序。我正在尝试在加载视图时将 JSON 对象从控制器传递到视图,以便 javascript 可以访问它。

The JSON looks like the following:

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"
        }
    }
}

The controller code looks like the following:

控制器代码如下所示:

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);
}

The view (some_view) code looks like the following:

视图 (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>

The javascript (some_script) code looks like the following:

javascript (some_script) 代码如下所示:

var some_data;

$(document).ready(function(){

    some_data = $.parseJSON(some_data);
});

The challenge is that since the JSON object is sent as a string (after json_encode) it has characters such as { and quotes as part of it, which the javascript does not like when I'm assigning it to a var (some_data = "";). I've tried using also but it does not work as well.

挑战在于,由于 JSON 对象是作为字符串发送的(在 json_encode 之后),它包含 { 和引号等字符作为其中的一部分,当我将它分配给 var (some_data = "" ;) 我也试过使用,但效果不佳。

I tried doing a bunch of things which did not work, in order to make progress I temporarily ended up replacing the " in the controller $data['some_data'] = str_replace('"', """, $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('"', "&quot;", $some_data);
    );

    $this->load->view('some_view',$data);
}

and replacing the " back to " inside the javascript some_data = some_data.replace(/"/g, '"');

并在javascript some_data = some_data.replace(/"/g, '"'); 中替换“ back to ”;

var some_data;

$(document).ready(function(){

    event_data = event_data.replace(/&quot;/g, '"');
    some_data = $.parseJSON(some_data);
});

This is kind of ugly and i'm looking for a better solution.

这有点难看,我正在寻找更好的解决方案。

Any pointers will be greatly appreciated.

任何指针将不胜感激。

Update!Problem solved, looks like extra quotes were breaking things.

更新!问题解决了,看起来额外的引号破坏了事情。

The solution is inline with mohan.gade's answer:

解决方案与 mohan.gade 的回答一致:

Controller:

控制器:

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);
}

View:

看法:

    some_data = <?php echo $some_data?>;

</script>

采纳答案by mohan.gade

Your JSON values was not getting pass to the view, try corrected following code.

您的 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>

回答by Tim Post

This can be done safely without a lot of code, provided that you have some sanity in your model. The JSON you posted leads me to believe that you have a database containing events, and an event either exists or it doesn't.

这可以在没有大量代码的情况下安全地完成,前提是您的模型具有一定的理智。你发布的 JSON 让我相信你有一个包含事件的数据库,一个事件要么存在,要么不存在。

If $this->Some_model->get_some_data()returns a typed FALSEor NULLthat can be verified with the equality operator if no results exist, you can safely express this to your JS in the view in the same way that you could convey the JSON.

如果$this->Some_model->get_some_data()返回一个类型化的FALSENULL可以在没有结果的情况下使用相等运算符进行验证,您可以安全地在视图中以与您可以传达 JSON 相同的方式将其表达给您的 JS。

E.g:

例如:

$some_data = $this->Some_model->get_some_data();
if ($some_data === NULL) {
     $data['somedata'] = 'null';
} else {
     // We trust our model, pass it along.
     $data['somedata'] = json_encode($some_data);
}
$this->load->view('some_view', $data);

Then, in your JS, simply verify that the variable that would contain the raw JSON string is in fact not null prior to operating on it. You could also just set it as an integer, the point is make it easy to differentiate.

然后,在您的 JS 中,在对其进行操作之前,只需验证将包含原始 JSON 字符串的变量实际上不为空。您也可以将其设置为整数,重点是易于区分。

From the looks of it, if event(s) actually exist, you'll at least have the event data and the person creating it as a member. You may need to do more sanity checking than that, I'm not sure what's in your model.

从它的外观来看,如果事件确实存在,您至少将拥有事件数据和创建它的人作为成员。您可能需要进行更多的完整性检查,我不确定您的模型中有什么。

Just make sure the PHP variable is expanded in a syntactically correct way within your JS, or perhaps elect to alter the JS entirely if no data exists to feed it.

只需确保在您的 JS 中以语法正确的方式扩展 PHP 变量,或者如果不存在数据来提供它,则可能选择完全更改 JS。

回答by Cauliturtle

json_encode will return nullif empty variable passed, so you no need to escape "it in you view code. instead, you have to check the variable is array or is object to pass in to generate different code.

null如果传递了空变量,json_encode 将返回,因此您无需"在查看代码中对其进行转义。相反,您必须检查变量是数组还是要传入的对象以生成不同的代码。

For you example:

以你为例:

if( is_array( $_var_value ) || is_object( $_var_value) ){
    echo 'var ' . $_var_name . ' = ' . json_encode( $_var_value ) . ";";
}else{ // if( is_string( $_var_value ) ){
    echo 'var ' . $_var_name . ' = "' .  $_var_value  . '";';
}

Updated for you case

为您更新案例

 <script type="text/javascript">
     <?php if( is_array( $_var_value ) || is_object( $_var_value) ){ ?>
     var some_data = <?php echo json_encode($some_data); ?>;
     <?php }else{ ?>
     var some_data = "<?php echo $some_data; ?>";
     <?php } ?>
 </script>