javascript - 无法使用 Ajax 读取 JSON 数据

标签 javascript jquery ajax json

打开“http://localhost/uebung/index.html”时仅显示 HTML/CSS(无法读取 JSON)

JSON 数据(目前有效):

<?php
$array = array(
  array(
    "title" => "Erster Eintrag",
    "description" => "Hier kommt eine Beschreibung hin!",
    "link" => "http://",
    "pubDate" => "02.07.2015"
  ),
  array(
    "title" => "Zweiter Eintrag",
    "description" => "Hier kommt eine Beschreibung hin!",
    "link" => "http://",
    "pubDate" => "02.07.2015"
  )     
);
echo json_encode($array);?>

html文件(此文件无法读取json文件):

<script type="text/javascript">
    $.ajax({
      url:'http://localhost/uebung/staticfeed.php',
      type:'POST',
      data: val,
      dataType: 'json',
      success: function(data){
        $.each(data, function(key, val){
          $('#feeds').append('<div id="' + key + '">' + val.title + ' ' + val.description + ' ' + val.link + ' ' + val.pubDate + '</div>');
        });

      }
    })
  </script>
  <div id="feeds">dsf
  </div>

最佳答案

这样写可以告诉你的脚本你正在发送 JSON

header("Content-Type: application/json", true);
echo json_encode($array);?>

在迭代之前解码 JSON。

success: function(data){
        data = $.parseJSON(data);
        $.each(data, function(key, val){
        ....

关于javascript - 无法使用 Ajax 读取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31188295/

相关文章:

javascript - 如何 .search() 多个字符串并至少有 1 个字符串才能起作用?

jquery - 语法错误 : invalid label using jQuery. ajax()

jquery - 我应该在 jQueryMobile 中使用 jQuery Ajax api 吗?

javascript - 将数组中的 json 对象字符串化,等于日期

javascript - 结合 ('click' ) 和 $(this)

javascript - 设置范围时间,然后使用 JavaScript/jQuery 移动到另一个时间段时进行更新

javascript - 使用 javascript 定位由 ajax 插入的按钮

javascript - Jasmine/Karma 测试 Angular 5 HTTP 响应

javascript - JSON 解析后无法读取未定义的属性

javascript - React循环组件除了一个元素