简体   繁体   English

在视图中将变量从控制器传递到javascript

[英]Pass a variable from controller to javascript in view

I'm trying to pass a variable from the controller to the view through JSON. 我正在尝试通过JSON将变量从控制器传递到视图。 The data that I want to check is available but if I try to access it like "data.status" it comes back as undefined. 我要检查的数据可用,但是如果我尝试像“ data.status”一样访问它,它将以未定义的形式返回。

The code that I use in the controller is: 我在控制器中使用的代码是:

public function checkserie(){
    $data['status'] = 'success';
    $this->output->set_output(json_encode($data, JSON_PRETTY_PRINT));
}

And the code that I use in the view is: 我在视图中使用的代码是:

$.post('<?php echo base_url("index.php/manageorderseries/checkserie")?>', { name: $("#seriename").val()}).done(function(data) {
        alert(data.status);
});

I also saw that when I replace "data.status" with just "data", I receive the following in my alert: 我还看到当我仅用“数据”替换“ data.status”时,在警报中收到以下消息:

{status: "success"}

What did I miss to access the variable as "data.status"? 我错过了什么来访问变量“ data.status”?

Thanks in advance ! 提前致谢 ! Kind regards, 亲切的问候,

Jonas Vandevelde 乔纳斯·范德维尔德

The response you are getting is JSON, so JS needs to parse that if you want to use it like an ordinary JS object. 您得到的响应是JSON,因此,如果您想像普通的JS对象一样使用它,则JS需要对其进行解析。

You can use either JSON.parse() or $.parseJSON() (since you already are using jQuery) to accomplish this. 您可以使用JSON.parse()$ .parseJSON() (因为您已经在使用jQuery)来完成此操作。

$.post('<?php echo base_url("index.php/manageorderseries/checkserie")?>', { name: $("#seriename").val()}).done(function(data) {
    var dataObj = JSON.parse(data);
    alert(dataObj.status);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM