PHP:导出一个JSON文件并用JS捕获它


PHP: Export a JSON file and catch it by JS

php代码:

<?php
 $date = date("Y/m/d");     
 echo json_encode($date);
?>

它导出一个json文件。然后,我想通过JS:

捕获它
$.get("/your/url").done(function(data){
});

但我的问题是-我怎么能知道JSON文件保存在哪里(如果它甚至被保存)?

是否echo json_encode($date)导出json文件到某个地方?还是说echo跟这没关系?

谢谢你的帮助。

Edit:有人能帮我吗?

你在php方面做得很好,但在jquery方面我不知道$.get().done()是否有效

我这样用过,效果很好

$.getJSON( "url/yoururl", function( data ) { 
  console.log(data);
});

也可以使用

$.ajax({
method:GET,
url:'url/yoururl',
success:function(data){
   console.log(data);
}
});

console.log(data)将返回您从php导出的日期

我不使用jQuery,但概念是相同的。

001 - tmp.php

<?php
    $date = date("Y/m/d");     
    echo json_encode($date);
?>
001 - tmp.html

<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id)}
function ajaxGet(url, onLoad, onError)
{
    var ajax = new XMLHttpRequest();
    ajax.onload = function(){onLoad(this);}
    ajax.onerror = function(){console.log("ajax request failed to: "+url);onError(this);}
    ajax.open("GET",url,true);
    ajax.send();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
    byId('goBtn').addEventListener('click', onBtnClick, false);
}
function onBtnClick(evt)
{
    ajaxGet('001-tmp.php', onLoad, onError);
    function onLoad(ajax)
    {
        var rawData = ajax.responseText;
        var parsedData = JSON.parse(rawData);
        byId('ajaxTarget').innerHTML = parsedData;
    }
    function onError(ajax)
    {
        // todo: add something useful here
    }
}
</script>
<style>
</style>
</head>
<body>
    <button id='goBtn'>Get data from PHP</button>
    <div id='ajaxTarget'></div>
</body>
</html>