How to get JSON from PHP to JS?

I really searched for almost 2 hours and have not yet found a good example of how to transfer JSON data from PHP to JS. I have a JSON script encoding in PHP that displays a JSON script that looks more or less similar (pseudocode).

{
"1": [
  {"id":"2","type":"1","description":"Foo","options:[
    {"opt_id":"1","opt_desc":"Bar"},
    {"opt_id":"2","opt_desc":"Lorem"}],
  {"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
  {"id":"14","type":"1","description":"Test","options:[
...
etc

The problem is, how can I get this data using JavaScript? My goal is to create a .js script that generates a survey based on JSON data, but I'm honest with God, I can not find examples of how to do this. Guess this is something like:

Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
  enter code here
}

Any links to any good examples or similar could be greatly appreciated. And I thought encoding data in PHP was a difficult part ...

EDIT:

, JSON JS. , . (1-6), , , . ?

$(document).ready(function()
    {       
        $('#show-results').click(function() 
        {
            $.post('JSAAN.php', function(data) 
            {
                var pushedData = jQuery.parseJSON(data);
                $.each(pushedData, function(i, serverData)
                {
                    alert(i);
                })
            })
        })
    });

, qusetion, - ( ), checkbox/radiobutton , . , . , 6 , / div , Ajax.

+5
4

, ,

$.getJSON('url', data, function(jsonData) {                       
  // operate on return data (jsonData)    
});

PHP json, getJson,

var neededData; 
$.getJSON('url', data, function(jsonData) {
    neededData = jsonData; 
});       
+6

jQuery: http://api.jquery.com/jQuery.getJSON/

:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

JSON:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}
+5

JQuery, , : http://api.jquery.com/jQuery.getJSON/.

Otherwise, I just want you to explain that there is no way to access JSON directly in JavaScript, as you tried in your code above. The main thing is that JavaScript works in your browser while your PHP script is running on your server. Therefore, between them must be communication. Therefore, you should request data from the server via http, which I suggest.

NTN

+2
source

All Articles