how to get data to javascript from php using json_encode?
I am trying to map traceroutes to google maps.
I have an array in php with traceroute data as
$c=ip,latitude,longitude, 2开发者_如何学Cnd ip, its latitude, longitude, ....target ip, its lat, its lng
I used json_encode($c, JSON_FORCE_OBJECT)
and saved the file
Now, how do I access this using javascript, by directly equating it to new JS object?
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
data=data12.route;
and then simply acces the members as data[1].latitude
I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.
For parsing JSON, simply do
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.
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):
$.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:
<?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. 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:
<!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. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.
no need for jquery, just:
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:
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
<select name="sub" id="subcat" class="form-control" required="required">
</select>
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
$("#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');
}
});
精彩评论