我正在向 url 发送 ajax 请求并得到以下响应:
Ajax 请求:
<div id="htmldata"></div>
<script type="text/javascript">
jQuery.ajax({
type: "GET",
url: "http://testing.local/index.php",
dataType: "html",
success: function(response) {
// Parse response here ...
}
});
</script>
响应:
<div class="dataset">
<h1 class="title">List of Data</h1>
<table width="100%" align="center" class="datatable" >
<tr>
<td class="dataField" ><label>Data 1</label></td>
<td class="dataValue">Value 1</td>
</tr>
<tr>
<td class="dataField" ><label>Data 2</label></td>
<td class="dataValue">Value 2</td>
</tr>
<tr>
<td class="dataField" ><label>Data 3</label></td>
<td class="dataValue">Value 3</td>
</tr>
</table>
</div>
{"status":"success", "message":"Received data successfully"}
在ajax响应中,有两种类型的数据,json和html。
所以我想提醒来自 json 数据的成功或失败消息,并使用 jQuery 或 javascript 在 ID 为“htmldata”的 div 中设置 html 代码。
最佳答案
像这样让你的json对象:
$form = '<div class="dataset">
<h1 class="title">List of Data</h1>
<table width="100%" align="center" class="datatable" >
<tr>
<td class="dataField" ><label>Data 1</label></td>
<td class="dataValue">Value 1</td>
</tr>
<tr>
<td class="dataField" ><label>Data 2</label></td>
<td class="dataValue">Value 2</td>
</tr>
<tr>
<td class="dataField" ><label>Data 3</label></td>
<td class="dataValue">Value 3</td>
</tr>
</table>
</div>';
// Handle Success Message
echo json_encode(array( 'status'=>'success',
'message'=>'Received data successfully',
'html'=>$form));
// Handle Failure Message
/*echo json_encode(array( 'status'=>'fail',
'message'=>'Something went wrong',
'html'=>$form));
*/
在成功
和失败
两种情况下,它都会返回表单,
现在 Javascript 转:
jQuery.ajax({
type: "GET",
url: "http://testing.local/index.php",
dataType: "json",
success: function(response) {
console.log(response.status);
console.log(response.message);
console.log(response.html);
}
});
就是这样
关于javascript - 从 ajax 响应中解析 json 和 html 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25759755/