【问题标题】:how can I access json data from another url inside a html page如何从 html 页面中的另一个 url 访问 json 数据
【发布时间】:2017-04-11 23:53:54
【问题描述】:

这是我的 php 代码,它将返回 json 数据类型

$sql="SELECT * FROM POST";
$result = mysqli_query($conn, $sql);
$sJSON = rJSONData($sql,$result);
echo $sJSON;


function rJSONData($sql,$result){
    $sJSON=array();
    while ($row = mysqli_fetch_assoc($result))
    {
        $sRow["id"]=$row["ID"];
        $sRow["fn"]=$row["posts"];
        $sRow["ln"]=$row["UsrNM"];
        $strJSON[] = $sRow;
    }
    echo json_encode($strJSON);
}

这段代码会返回

 [{"id":"1","fn":"hi there","ln":"karan7303"},
 {"id":"2","fn":"Shshhsev","ln":"karan7303"},
 {"id":"3","fn":"karan is awesome","ln":"karan7303"},
 {"id":"4","fn":"1","ln":"karan7303"},
 {"id":"5","fn":"asdasdas","ln":"karan7303"}]

但是我如何在 html 中访问这些数据,也就是说,我想要特定位置的特定数据,例如我想在我的 div 中显示“fn”,在另一个 id 的另一个 div 中显示“ln”

在尝试其他方法之前,我尝试了这个

$.ajaxSetup({ 
  url: 'exm1.php', 
  type: 'get', 
  dataType: 'json',
  success: function(data){
    console.log(data);          
  }
});

但它显示数据未定义我不知道我做错了什么

【问题讨论】:

  • $.ajaxSetup 换成$.ajax。此外,您的 rJSONData 函数不会返回任何内容。我会将echo json_encode($strJSON) 更改为return json_encode($strJSON)
  • 试过没用
  • 使用$.ajax 函数代替$.ajaxSetup。看到这个帖子stackoverflow.com/questions/43356693/…
  • @SahilVerma 抱歉,我在上面的评论中添加了更多内容
  • @Phil 试过还是不行,我认为这不是问题,因为 php 文件还是返回了 json 数据

标签: php jquery json


【解决方案1】:

如果您将$.ajaxSetup(这是一种全局配置方法)与$.ajax 交换,那么您所拥有的应该某种 可以工作。不过,您可以进行一些重大改进。

例如,您的 PHP 围绕 rJSONData 返回的值做了一些奇怪的事情。这里有一些修复

function rJSONData($result) {
    $sJSON = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $sJSON[] = array(
            'id' => $row['ID'],
            'fn' => $row['posts'],
            'ln' => $row['UsrNM']
        );
    }
    return json_encode($sJSON);
}

当你调用它时

header('Content-type: application/json');
echo rJSONData($result);
exit;

还要确保您没有通过echo / print 或HTML(例如<html> 等)输出任何其他数据


在你的 JavaScript 中,你可以通过使用来大大简化你的代码

$.getJSON('exm1.php', function(data) {
  console.info(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
  console.error(jqXHR, textStatus, errorThrown);
});

【讨论】:

  • 它给出解析错误 parsererror" SyntaxError: Unexpected token ) at m.parseJSON (jquery.min.js:4) at Pc (jquery .min.js:4) 在 x (jquery.min.js:4) 在 XMLHttpRequest.b (jquery.min.js:4) (匿名) @ exm.php:35 j @ jquery.min.js:2 fireWith @jquery.min.js:2 x @jquery.min.js:4 b @jquery.min.js:4
  • 我也不能使用你的 rJSONData 函数,因为它在 sJSON=[];行所以我使用了我的 rJSONData 函数上一个
  • 那工作我发现错误出现在我的 php 中,我在开始时使用 和
  • @SahilVerma 如果不支持数组字面量,听起来您正在使用 very 旧版本的 PHP。我已经更新了我的答案以使用旧语法
  • 其实我对所有这些 JSON Ajax PHP 东西都是新手所以不太了解新旧事物
【解决方案2】:

使用$.ajax 代替$.ajaxSetup 函数。

这是另一个 SO 帖子 how to keep running php part of index.php automatically? 的详细答案

<script>

$.ajax({
    // name of file to call
    url: 'fetch_latlon.php',

    // method used to call server-side code, this could be GET or POST
    type: 'GET'

    // Optional - parameters to pass to server-side code
    data: {
        key1: 'value1',
        key2: 'value2',
        key3: 'value3'
    },

   // return type of response from server-side code
   dataType: "json"

    // executes when AJAX call succeeds
    success: function(data) {
        // fetch lat/lon
        var lat = data.lat;
        var lon = data.lon;

        // show lat/lon in HTML
        $('#lat').text(lat);
        $('#lon').text(lon);
    },

    // executes when AJAX call fails
    error: function() {
        // TODO: do error handling here
        console.log('An error has occurred while fetching lat/lon.');
    }
});


</script>

【讨论】:

  • 在我的情况下,它显示获取纬度/经度时发生错误。这个错误是因为我复制了那个 console.log 行
  • 您是否更改了代码的适当部分以匹配您的代码,例如 urldata
  • 是的,我确实只是复制了错误语句以确保它是否给出错误
  • 在浏览器中访问您的PHP 文件(如果它有效)并回显您的JSON?
  • 将我的回答标记为正确,以指导其他有类似问题的人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 2019-08-04
  • 2018-12-16
相关资源
最近更新 更多