【发布时间】: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 表。
如果有人能帮我解决这个问题,我将不胜感激
【问题讨论】: