简体   繁体   English

如何使用json_encode从php获取数据到javascript?

[英]how to get data to javascript from php using json_encode?

I am trying to map traceroutes to google maps.我正在尝试将 traceroutes 映射到谷歌地图。

I have an array in php with traceroute data as我在 php 中有一个带有 traceroute 数据的数组

$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng

I used json_encode($c, JSON_FORCE_OBJECT) and saved the file我使用了json_encode($c, JSON_FORCE_OBJECT)并保存了文件

Now, how do I access this using javascript, by directly equating it to new JS object?现在,如何使用 javascript 直接将其等同于新的 JS 对象来访问它?

earlier I used to have a data format like this on harddrive早些时候我曾经在硬盘上有这样的数据格式

var data12 = {

"route":[
{
    "ip": "some ip",

    "longitude": "some lng",

    "latitude": "some lat",

.....

and in my javascript it was used as在我的 javascript 中它被用作

data=data12.route;

and then simply acces the members as data[1].latitude然后简单地将成员作为 data[1].latitude 访问

I recommend using the jQuery library .我建议使用jQuery 库 The minified version only has 31 kB in size and provides lots of useful functions.缩小版只有 31 kB 大小,并提供了许多有用的功能。

For parsing JSON, simply do要解析 JSON,只需执行

var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );

You can now access everything easily:您现在可以轻松访问所有内容:

alert ( obj.name );

Note : jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.注意:jQuery 使用浏览器的本机 JSON 解析器 - 如果可用 - 这比使用eval ()方法非常快速且安全。

Edit : To get data from the server side to the client side, there are two possibilities:编辑:要从服务器端获取数据到客户端,有两种可能:

1.) Use an AJAX request (quite simple with jQuery): 1.) 使用 AJAX 请求(使用 jQuery 非常简单):

   $.ajax ( {
       url: "yourscript.php",
       dataType: "json",
       success: function ( data, textStatus, jqXHR ) {
           // process the data, you only need the "data" argument
           // jQuery will automatically parse the JSON for you!
       }
   } );

2.) Write the JSON object into the Javascript source code at page generation: 2.) 在页面生成时将 JSON 对象写入 Javascript 源代码:

   <?php
       $json = json_encode ( $your_array, JSON_FORCE_OBJECT );
   ?>

   <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>

   <script type="text/javascript">
   //<![CDATA[

   var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );

   //]]>
   </script>

I know this is old, but I recently found myself searching for this.我知道这是旧的,但我最近发现自己在寻找这个。 None of the answers here worked for my case, because my values had quotes in them.这里的答案都不适用于我的情况,因为我的值中有引号。 The idea here is to base64 encode the array before echo'ing to the page.这里的想法是在回显到页面之前对数组进行 base64 编码。 That way the quotes don't conflict.这样引号就不会冲突了。

< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);

I could get the JSON array by using PHP's json_encode() from backend like this example:我可以使用 PHP 的 json_encode() 从后端获取 JSON 数组,如下例所示:

<!doctype html>
<html>
    <script type="text/javascript">
        var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
        console.log(json[1]);
        console.log(json.abc);
    </script>        
</html>

No quotation marks means an eval() of whatever was printed out.没有引号意味着打印出来的任何东西的 eval() 。 This is a quick hack that we utilised often to quickly add initial values to our AJAX page.这是我们经常用来快速向 AJAX 页面添加初始值的快速技巧。

no need for jquery, just:不需要jquery,只需:

    var array= <?php echo json_encode($array); ?>;
    console.log(array->foo);

we have to display the json encode format in javascript , by using below one:我们必须在 javascript 中显示 json 编码格式,使用以下之一:

var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);

This function works for you I guess:我猜这个功能对你有用:

    function json_encode4js($data) {
    $result = '{';
    $separator = '';
    $count = 0;
    foreach ($data as $key => $val) {

        $result .= $separator . $key . ':';
        if (is_array($val)){
            $result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
            continue;
        }
        if (is_int($val)) {
            $result .= $val;
        } elseif (is_string($val)) {
            $result .= '"' . str_replace('"', '\"', $val) . '"';
        } elseif (is_bool($val)) {
            $result .= $val ? 'true' : 'false';
        } elseif (is_null($val)) {
            $result .= 'null';
        } else {
            $result .= $val;
        }

        $separator = ', ';
        $count++;
    }

    $result .= '}';

    return $result;
}

$a = array(
"string"=>'text',
'jsobj'=>[
    "string"=>'text',
    'jsobj'=>'text2',
    "bool"=>false
    ],
"bool"=>false);

var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}" 

var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"

HTML HTML

<select name="sub" id="subcat" class="form-control" required="required">

</select>

PHP PHP

$this->load->model('MainModel');
$subvalue = $this->MainModel->loadSubData($var);
echo json_encode($subvalue);
//if MVC
// or you can just output your SQLi data to json_encode()

JS JS

$("#maincat").change(function(){
  var status = this.value;

  $.ajax({
    type: 'POST',
    url: 'home/subcat/'+status,
    success: function(data){
        var option = '';
        var obj = JSON.parse(data);
        if(obj.length > 0){
            for (var i=0;i<obj.length;i++){
            option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';  
            }
            //Now populate the second dropdown i.e "Sub Category"
            $('#subcat').children("option").remove();
            $('#subcat').append(option);
        }else{
            option = '<option value="">No Sub Category Found</option>';
            $('#subcat').children("option").remove();
            $('#subcat').append(option);
        }       
    },
    error: function(){
    alert('failure');
    }
});

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

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