【问题标题】:Generate json with url built from form使用从表单构建的 url 生成 json
【发布时间】:2015-01-23 21:55:04
【问题描述】:

我正在尝试创建一个能够生成多个 url 的表单,具体取决于用户的输入。创建的 url 具有 json 扩展名。一个 php 文件用于获取该 url 的内容。此 php 文件必须与输入的 url 具有相同的内容。此 php 文件用作 javascript/jquery 文件的输入。

在这个文件中,我试图将 json 代码转换为 html 表。这是由 http_request 完成的。该表必须在 html 页面上的 div 中输出。但是,由于找不到错误,我的代码不起作用。我已经在 stackoverflow 和 google 上查看了类似的问题,但可以找到使我的代码正常工作的修复程序。

我正在应用此代码来识别列表。这是我已有的代码:

html:

<script type="text/javascript" src="spotify.js"></script>
<form id="spotifyform" action="spotifylist.php" method="post">
      <select id="country" name="country">
        <option value="GB">UK</option>
        <option value="US">USA</option>
      </select>
      <select id="interval" name="interval">
        <option value="daily">Daglijst</option>
        <option value="weekly">Weeklijst</option>
      </select>
      <select id="chart" name="chart">
        <option value="most_streamed">Meest gestreamd</option>
        <option value="most_viral">Meest gedeeld</option>
      </select>
      <input type="submit" name="formSubmit" value="Submit"/>
</form>
<div id="spotifylist"></div>

spotify.js:

function loadJSON()
{
    var http_request = new XMLHttpRequest();
    try{
      // Opera 8.0+, Firefox, Chrome, Safari
      http_request = new XMLHttpRequest();
    }catch (e){
      // Internet Explorer Browsers
      try{
         http_request = new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e) {
         try{
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         }catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
         }
      }
    }

   http_request.open("GET", "spotifylist.php", true);
   http_request.send();
   http_request.onreadystatechange  = function(){
      if (http_request.readyState == 4  )
      {
        // Javascript function JSON.parse to parse JSON data
        var jsonObj = JSON.parse(http_request.responseText);

        // jsonObj variable now contains the data structure and can
        // be accessed as jsonObj.artist_name and jsonObj.track_name.

        HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th   id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
        var x=jsonObj.tracks;
        for (i=0;i<x.length;i++)
          { 
        HTML += "<tr id='row1'><td id='dw'>";
        HTML += i+1;
        HTML += "</td><td id='song'>";
        HTML += x[i].artist_name;
        HTML += "</td><td id='song'>";
        HTML += x[i].track_name;
        HTML += "</td></tr>";
          }
        HTML += "</tbody></table>";

        document.getElementById("spotifylist").innerHTML = HTML; 

      }
    }
 }

$("#spotifyform").submit(function(){
    loadJSON();
    return false;
});

spotifylist.php

<?php 
if($_POST['formSubmit'] == "Submit") 
{
   $chart = $_POST['chart'];
   $country = $_POST['country'];
   $interval = $_POST['interval'];
}

$data_file="http://charts.spotify.com/api/tracks/".$chart."/".$country."/".$interval."/latest";
$url = file_get_contents ($data_file);
echo $url;
?>

目前的问题是当我按下提交按钮时加载了 php 文件。该文件包含正确的 json 信息。但是这个 json 并没有转换成 html 表。

如果有人能帮我解决这个问题,我将不胜感激

【问题讨论】:

    标签: php jquery json forms


    【解决方案1】:

    如果您希望 spotifylist div 在您按下提交时加载数据,您必须阻止页面重定向。

    制作表单动作:

    &lt;form action="&lt;?php echo htmlspecialchars($_SERVER['PHP_SELF'])?&gt;

    如果可能,您的输入值(如果您在表单标签中有任何值):

    "<?php echo $_POST['value']?>"
    

    如果可以,请将您的 HTML 代码放在一个 PHP 文件中,该文件执行来自 spotifylist.php 的所有内容。

    【讨论】:

    • 不幸的是,这不起作用,因为表单不再向 spotifylist.php 发送数据。因此,spotifylist.php 的内容不会输入到 javascript 函数中(仅测试您的第一条评论)。
    • 您的 HTML 表单是否包含在 PHP 文件中?
    • 问:您的 HTML 表单是在 PHP 文件中吗?答:是的。在名为 spotify.php 的文件中
    • 我将html文件(spotify.php)的全部内容复制到spotifylist.php,当我提交表单时,输出的是正确url(json数据)的echo(file_get_contents)。但是 div 仍然是空的(没有表格)。
    • 这意味着您必须从使用 JS 文件的 $url 变量中获取数据。这是另一个与在不重定向的情况下运行 PHP 无关的问题。
    【解决方案2】:

    我猜有几个问题。

    您将表单发送到 spotifylist.php,它会抓取一个文件并将某些内容发送回 html。可能是 JSON,但你在哪里处理这些数据? 也许一些 Javascript 对你的 php 发回的“字符串”做一些事情?

    并且您的 loadJSON(无论何时)向同一个 php 发送一个 GET 请求,但没有参数或其他东西。 所以你的 php 遇到错误,因为显然没有设置 POST 变量,所以你的 if 条件中的变量永远不会设置你的数据,它又回来了?!?有错误

    你应该先弄清楚你想使用哪种技术。

    在我看来,两者都需要一点。

    【讨论】:

    • 我宁愿只在 javascript 中解决这个问题。然而这是不可能的,因为对外部服务器的 httprequest 不起作用(在这种情况下)。因此我需要 file_get_contents。
    • 没错。你可以这样做,但是你必须在同一个请求中从 php 发回数据,所以如果你从你的 javascript 以 GET 请求的形式发出第二个请求,那么从第一个 POST 中提取的数据将不再可访问。跨度>
    • 所以现在的主要问题是 php 文件没有在正确的时刻(提交时)发送到 javascript。您能给我一些建议吗?如何解决这个问题?
    【解决方案3】:
      有多种方法可以从外部服务器获取信息:

  • httprequest - 不推荐,因为糟糕的用户体验。
  • file_get_contents - 通常很容易,但在这种情况下,它需要大量的数据处理。 PHP 在服务器端工作,javascript 在客户端工作。让这两者一起工作需要做更多的工作。
  • $.ajax - 在这种情况下是最好的解决方案,因为它不需要任何 php 并且 $.ajax 能够直接解析 json 数据。由于数据是从外部站点请求的,因此您必须将数据类型更改为 jsonp 并执行回调函数。

  • 将数据从表单传输到javascript非常容易:

    // Automatically call this function when the page loads.
    window.onload = function loadJSON()
    {
      // The HTML input of the form that is the input of this javascript document
      var country2 = document.getElementById("country");
      var chart2 = document.getElementById("chart");
      var interval2 = document.getElementById("interval");
    

    使用提交时选择的参数构建 url:

    // Call the function when the form is submitted
      $("#spotifyform").submit(function(e)
      {
        e.preventDefault(); // to prevent the page from reloading
    
        // Save the choice of the <select> country in a variable named country2
        var country = country2.options[country2.selectedIndex].value;
        var chart = chart2.options[chart2.selectedIndex].value;
        var interval = interval2.options[interval2.selectedIndex].value; 
        var url = "http://charts.spotify.com/api/tracks/" + chart + "/" + country + "/" + interval + "/latest"; // build url
    

    然后得到正确的数据,直接用json原生解析器解析。

    // Get the data from the site and save this into the variable 'json'
        $.ajax
        ({
          'url': url + '?callback=?', // ?callback=? lets the server generate a function name, the call can be handled in the success parameter
          'dataType': 'jsonp', // Cross site request via jsonp
          'error': function(xhr, status, error){ alert(error.message); },
          'success': jsonParser // call function
        }); // $.ajax  
    
      }); // $("#spotifyform").submit(function(e)
    } // window.onload = function loadJSON()
    

    然后随心所欲地处理数据。您无需执行 httprequest,也无需再解析数据。

    function jsonParser(json) 
    {
      HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
      var x=json.tracks;
      for (i=0;i<x.length;i++)
        { 
        HTML += "<tr id='row1'><td id='dw'>";
        HTML += i+1;
        HTML += "</td><td id='song'>";
        HTML += x[i].artist_name;
        HTML += "</td><td id='song'>";
        HTML += x[i].track_name;
        HTML += "</td></tr>";
        }
      HTML += "</tbody></table>";
      document.getElementById("spotifylist").innerHTML = HTML; 
    } // function jsonParser(json)
    

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多