【发布时间】:2017-08-06 09:50:57
【问题描述】:
我正在尝试将使用 PHP 从 MySQL DB 获取的 JSON 数据显示到 HTML 元素中,比如表格。下面是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Test Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#display").change(function()
{
var type = document.getElementById('display').value;
$.ajax(
{
//create an ajax request to load_page.php
type: "POST",
url: "DBOperations.php",
data : "type=" +type,
dataType: "text", //expect text to be returned
success: function(response)
{
var tr = $('<tr>');
tr.append('<td>' + response.client_id + '<td>');
tr.append('<td>' + response.client_name + '<td>');
tr.append('<td>' + response.client_title + '<td>');
tr.append('<td>' + response.client_type + '<td>');
$('#myTable').append(tr);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});
});
});
</script>
</head>
<body>
<form>
<select id="display" name="clienttype" onchange="showClient(this.value)">
<option value="">Select a Client:</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</form>
<br>
<table id="myTable">
<tr>
<th>ClientID</th>
<th>ClientName</th>
<th>ClientTitle</th>
<th>ClientType</th>
</tr>
</table>
</form>
</body>
</html>
这是我从 php 作为 JSON 得到的:
[{"client_id":"1","0":"1","client_name":"asdf","1":"asdf","client_title":"asdf","2":"asdf","client_type":"a","3":"a"}]
如果我将 AJAX 中的数据类型设置为 json,它会显示如下问题中的错误: how to remove parsererror: SyntaxError: Unexpected token < in JSON at position 0
所以我将其保留为 html 或文本,至少显示没有错误的响应。但我需要格式化响应并将其提供给另一个元素。
提前致谢。
【问题讨论】: