Home>
Name = Hamburg, Classification = Western food, Principal component = Protein
Name = Sushi, Classification = Japanese, Main ingredient = Carbohydrate
Name = Milk, Classification = Drink, Main ingredient = Calcium
$fp = fopen ("test.txt", "r");
while (($data = fgetcsv ($fp, 1024))! == false) {
  $tmp =&$datas [];
  foreach ($data as $x) {
    $y = explode ("=", $x);
    $tmp [trim ($y [0])] = trim ($y [1]);
  }
}
unset ($tmp);
fclose ($fp);
print json_encode ($datas, JSON_UNESCAPED_UNICODE);
$(function () {
     $("# button"). click (function (event) {
       $.ajax ({
         type: "GET",
         url: "test.php",
         data: {val: null},
         dataType: "text"
       }). done (function (data) {
           var test = JSON.parse (data);
           for (var key in data) {
         $("# parse"). append ('key:' + key + ': value:' + data [key] + "<br/>");
        }
       }). fail (function (XMLHttpRequest, textStatus, errorThrown) {
         alert (errorThrown);
       });
     });
   });

From the parsed data
Key: Name Value: Hamburg
Key: Classification Value: Western food
Key: Main component Value: Calcium
I want to do something like A huge number of keys and values ​​are displayed. What should I do?

If i run php alone and display before parse
[{"Name": "hamburger", "classification": "Western food", "main ingredient": "protein"}, {"name": "sushi", "classification": "Japanese food", "main ingredient": "Carbohydrate"}, {"Name": "Milk", "Classification": "Drink", "Main ingredient": "Calcium"}]
This is now

  • Answer # 1

    You didn't finish it yet ...

    $(function () {
      $("# button"). click (function (event) {
        $.ajax ({
        type: "GET",
        url: "test.php",
        data: {val: null},
        dataType: "json"
        }). done (function (data) {
          data.forEach (function (x) {
            Object.entries (x) .forEach (y =>{
              $("# parse"). append ('key:' + y [0] + ': value:' + y [1] + "
    ");         });       });     }). fail (function (XMLHttpRequest, textStatus, errorThrown) {       alert (errorThrown);     });   }); });

    test.php is a mechanism that returns json, so dataType should be json

    Since the return value data is an array, first turn it normally with for (or forEach)

    Use Object.entries to extract combinations from objects

    Direct from text
    $(function () {
      $("# button"). click (function (event) {
        $.ajax ({
        type: "GET",
        url: "test.txt",
        data: {val: null},
        dataType: "text"
        }). done (function (data) {
          var datas = [];
          for (var i of data.split ("\ n")) {
            for (var j of i.split (",")) {
              var k = j.split ("="). map (x =>x.trim ());
              $('# parse'). append ('key:' + k [0] + ': value:' + k [1] + "
    ");         }       }     }). fail (function (XMLHttpRequest, textStatus, errorThrown) {       alert (errorThrown);     });   }); });

Related articles