尝试通过JSON为ajax网站输出html.php。
php:
$return = "<div id='content'><ul class='allitems'>";
while($row = mysql_fetch_array($result)){
$return .= "<li class='items'>" . "<div class='itemheading'><div class='controls'> <span class='votes'>" . $row['votes'] . "</span>";
$return .= "<form class='actions' action='index.php' method='POST'><input type='hidden' name='id' value='{$row['id']}'/><input type='submit' class='button plus' value='+1' /></form>";
$return .= "<form class='actions' action='index.php' method='POST'><input type='hidden' name='id-' value='{$row['id']}'/><input type='submit' class='button minus' value='-1' /></form> ";
$return .= "<form class='actions' action='index.php' method='POST'><input type='hidden' name='idDel' value='{$row['id']}'/><input type='submit' class='button delete' value='X' /></form> ";
$return .= "</div><span class='title'>" . $row['name'] . "</span></div><span class='infotext'>". $row['infotext'] ."</span></li>";
}
$return .= "</ul></div>";
echo json_encode($return);
如果你转到这个php页面,输出的地方到处都是斜杠('/
),例如<'/span><'/form> <'/div>Make the app look all nice<'/span>
,并且不作为常规html输出。
这是将显示输出的ajaxpage的代码:
<script id="source" language="javascript" type="text/javascript">
$(function () {
$.ajax({url: 'retrieve.php', dataType: 'json'}).done(function(data) {
var html = data[3];
$('#output')
.append("<b>id: </b>"+html)
});
});
</script>
其问题在于当var html = rows[0];
时它输出<
,当[1]
等时输出d
。一次只显示1个字符。
我如何一次看到所有的html并将其作为实际的html代码?
JSON以类似数组的方式返回内容(我也是新的,所以我不太确定),所以你必须在数组中使所有html成为一个对象。下面,我将其设置为在关联数组中使用"html"进行引用。
在php页面上将此echo json_encode($return);
更改为echo json_encode(array('html' => $return));
在ajax页面上,您只需要对其进行一点更改。
替换:
var html = data[3];
$('#output')
.append("<b>id: </b>"+html)
带有:
var html = data['html'];
$('#content')
.append(html)
或者为了让它更整洁,你甚至不必为html创建一个变量,你可以直接从JSON数组中获取:
$('#content')
.append(data['html'])
您不必为此使用JSON;只需在jQuery中使用.load()将HTML片段直接加载到元素中。
$("#output").load("retrieve.php");