最近很多小伙伴都在问javascript-使用JSON响应的数据表和js使用json对象这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展javascript–CodeIgniter
最近很多小伙伴都在问javascript-使用JSON响应的数据表和js使用json对象这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展javascript – CodeIgniter – 如何从控制器返回Json响应、javascript – dc.js – 使用jquery data-table插件的数据表、javascript – IE iframe无法正确处理应用程序/ json响应、javascript – JSON响应中的重复块等相关知识,下面开始了哦!
本文目录一览:- javascript-使用JSON响应的数据表(js使用json对象)
- javascript – CodeIgniter – 如何从控制器返回Json响应
- javascript – dc.js – 使用jquery data-table插件的数据表
- javascript – IE iframe无法正确处理应用程序/ json响应
- javascript – JSON响应中的重复块
javascript-使用JSON响应的数据表(js使用json对象)
我正在尝试将来自Google购物的JSON响应加载到使用DataTables(即JQuery插件)格式化的html表中.
我将数据追加到表div中,但似乎不起作用.
<table cellpadding="0" cellspacing="0" border="0"https://www.jb51.cc/tag/dis/" target="_blank">display" id="example">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Currency</th>
<th>Price</th>
<th>Shipping</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Title</th>
<th>Currency</th>
<th>Price</th>
<th>Shipping</th>
</tr>
</tfoot>
</table>
<script>
var apiKey = "key";
var country = "US";
var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";
$(document).ready(function() {
$('#example').dataTable();
$('.button').click(function (e) {
$('#example').empty();
e.preventDefault();
$.ajax({
type: "GET",
url: apiurl,
dataType: 'jsonp',
data :
{
key: apiKey,
country: country,
q: $('[name=myanswer]').val()
},
success: function(data) {
$.each(data.items, function(i, item){
if (item.product.images.length > 0) // sanity check
{
//global variables
var link = item.product.images[0]['link'];
var title = item.product.title;
var gtin = item.product.gtins[0];
//price
var currency = item.product.inventories[0]['currency'];
var price = item.product.inventories[0]['price'];
var shipping = item.product.inventories[0]['shipping'];
var listData = "<li>" + title + gtin + price + currency + shipping + "</li>" + '<img title="' + title + '" src="' + link + '" />';
var dataTable =
"<tr>" +
"<td>" + '<img title="' + title + '" src="' + link + '" />' + "</td>" +
"<td>" + gtin + "</td>" +
"<td>" + title + "</td>" +
"<td>" + currency + "</td>" +
"<td>" + price + "</td>" +
"<td>" + shipping + "</td>" +
"</tr>";
$('#example').append(dataTable).hide().fadeIn('slow');
console.log(data)
}
});
}
});
});
});
更新:在Larry的帮助下,我设法将数据加载到表中.我知道这是因为底部填充了数字.但是,数据根本不显示.
<!DOCTYPE html>
<html>
<head>
<style>
#images { padding:0; margin:0; overflow: hidden;}
#images img { width:200px; height:200px; border:none;}
td {
padding-top: 2px;
padding-bottom: 2px;
padding-right: 20px;
}
#example img { width:50px; height: 50px; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.dataTables.js"></script>
</head>
<body>
<form id="myform">
<input type="text" name="myanswer" value="test">
<input type='submit'name="submitButton" value='submit'>
</form>
<table id="example">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>etc</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>etc</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
<td>etc</td>
</tr>
</tbody>
</table>
<script>
var apiKey = "key";
var country = "US";
var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";
$(document).ready(function() {
$('#example').dataTable();
$('.button').click(function (e) {
$('#example').empty();
e.preventDefault();
$.ajax({
type: "GET",
url: apiurl,
dataType: 'jsonp',
data :
{
key: apiKey,
country: country,
q: $('[name=myanswer]').val()
},
success: function(data) {
$.each(data.items, function(i, item){
if (item.product.images.length > 0) // sanity check
{
//global variables
var link = item.product.images[0]['link'];
var title = item.product.title;
var gtin = item.product.gtins[0];
//price
var currency = item.product.inventories[0]['currency'];
var price = item.product.inventories[0]['price'];
var shipping = item.product.inventories[0]['shipping'];
$('#example').dataTable().fnAddData( [
title,
gtin,
price
]);
}
});
}
});
});
});
</script>
</body>
</html>
解决方法:
假设您的AJAX调用正在工作并返回数据,将行追加到jQuery dataTable的正确方法不是尝试编辑基础HTML,而是让dataTable通过dataTable API调用fnAddData()添加该行.
有一个example here.
javascript – CodeIgniter – 如何从控制器返回Json响应
如何将控制器的响应返回给Jquery Javascript?
使用Javascript
$('.signinform').submit(function() {
$(this).ajaxSubmit({
type : "POST",
url: 'index.PHP/user/signin', // target element(s) to be updated with server response
cache : false,
success : onSuccessRegistered,
error: onFailRegistered
});
return false;
});
数据返回null(空白)!
function onSuccessRegistered(data){
alert(data);
};
控制器 –
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode( $arr );
}
解决方法:
//do the edit in your javascript
$('.signinform').submit(function() {
$(this).ajaxSubmit({
type : "POST",
//set the data type
dataType:'json',
url: 'index.PHP/user/signin', // target element(s) to be updated with server response
cache : false,
//check this in Firefox browser
success : function(response){ console.log(response); alert(response)},
error: onFailRegistered
});
return false;
});
//controller function
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
//add the header here
header('Content-Type: application/json');
echo json_encode( $arr );
}
javascript – dc.js – 使用jquery data-table插件的数据表
我想在表格中添加一些分页样式和搜索选项.
jQuery数据表脚本:
$(document).ready(function() { $('#data-table').DataTable(); })
问题是 – 我得到的所有jquery数据表选项显示为搜索框,条目数.但它们都不起作用.
有人请帮忙.
发现这个post.但没什么用.
解决方法
1)定义你的表格html:
<table id="dc-data-table"> <thead> <tr> <th data-dynatable-column="client_name">Client</th> <th data-dynatable-column="project_name">Project</th> </tr> </thead> </table>
2)使用您的首选选项和交叉过滤器维度挂钩dynatable:
var dynatable = $('#dc-data-table').dynatable({ features: { pushState: false },dataset: { records: tableDimension.top(Infinity),perPageDefault: 50,perPageOptions: [50,100,200,500,1000,2000,5000,10000] } }).data('dynatable');
3)编写一个刷新表的方法 – dc.events有助于限制刷子更改时调用的次数:
function RefreshTable() { dc.events.trigger(function () { dynatable.settings.dataset.originalRecords = tableDimension.top(Infinity); dynatable.process(); }); };
4)将此方法挂钩到每个图表过滤器事件中:
for (var i = 0; i < dc.chartRegistry.list().length; i++) { var chartI = dc.chartRegistry.list()[i]; chartI.on("filtered",RefreshTable); }
5)调用刷新表一次以显示当前数据:
RefreshTable();
6)渲染DC图表:
dc.renderAll();
这是一个jsfiddle:http://jsfiddle.net/djmartin_umich/5jweT/2/
请注意,在这个小提琴中,我使用组而不是维度来提供可动态数据.
javascript – IE iframe无法正确处理应用程序/ json响应
当更改它以使用我们的Web API端点(它返回Content-Type为“application / json”的响应)时,我们注意到Internet Explorer 9的问题.似乎从未调用过ajaxForm成功函数.据我所知,似乎IE中的iframe将Content-Type为“application / json”的响应正文解释为要下载的文件附件.这意味着它永远不会触发iframe的“已加载”事件,这意味着永远不会触发ajaxForm onload事件处理程序,并且永远不会调用我们的ajaxForm成功函数.
我们也注意到了IE 7中的问题,但是我们无法在最新版本的Firefox或Chrome中重新创建该问题,即使强迫他们使用iframe而不是使用FormData的File API.
为了解决此问题,我现在强制将响应Content-Type返回到“text / plain”,这是我们之前从处理文件上载的ASP.NET MVC控制器操作返回的内容.这使一切都恢复了.
我的问题:
>有没有办法可以将Web API响应Content-Type保持为“application / json”并让IE正确解释它?
>使用IE和Web API时是否有更好的文件上传方式?也许是一个不同的插件或更好的技术?
附加限制:我不能在本网站上使用ActiveX或Flash.我可以使用不同的插件,但前提是它具有一般的跨浏览器支持. (IE,Chrome,Firefox,Safari等)
我的HTML:
<form id="uploadFormId" action="" method="post" enctype="multipart/form-data" encoding="multipart/form-data"> <input type="file" name="files[]"/> </form>
我的javascript:
function onFileChange( e ) { if ( e.type === e.originalEvent.type ) { var filePath = $( e.currentTarget ).val(); if ( filePath !== '' ) { $( this ).closest( 'form' ).submit(); } } }; $( function() { $( '#uploadFormId' ).ajaxForm( { url: "api/Files/1234",dataType: 'json',success: function ( response ) { alert( response ); },error: function ( xhr,status,error ) { alert( status ); } } ); $( '#uploadFormId input[type="file"]' ).bind( 'change',onFileChange ); });
“application / json”响应头(在IE中不起作用):
Cache-Control:no-cache Content-Length:337 Content-Type:application/json; charset=utf-8 Date:Wed,17 Jul 2013 13:10:47 GMT Expires:-1 Pragma:no-cache Server:Microsoft-IIS/8.0 X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET
“text / plain”响应头(适用于IE):
Cache-Control:no-cache Content-Length:322 Content-Type:text/plain Date:Wed,17 Jul 2013 13:17:24 GMT Expires:-1 Pragma:no-cache Server:Microsoft-IIS/8.0 X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET
解决方法
使用text / plain也存在一个特定的问题,因为浏览器可能会内容嗅探它,并且如果在数据中看起来像HTML标记,则将资源视为HTML.如果您的JSON返回其中包含用户提供的数据,则可能允许某人将可执行JavaScript注入您的站点(XSS攻击).
正如ajaxForm doc所建议的,你应该检测到来自iframe帖子而不是AJAX的调用,并在这种情况下返回带有textarea包装器的text / html响应:
To account for the challenges of script and JSON responses when using the iframe mode,the Form Plugin allows these responses to be embedded in a textarea element and it is recommended that you do so for these response types when used in conjuction with file uploads and older browsers.
javascript – JSON响应中的重复块
我发现,当获得一个较大的(超过65536个字节)的json结果时,它使用gzip和chunked进行编码,但是返回的json无效,因为它包含两个答复!
例如{name:’hi’} {name:’hi’},用于数组的单个ID或[{..},{..}] [{..},{..}].
服务器api端点是从角度完整堆栈生成器自动生成的,如下所示:
// Get list of worlds exports.index = function(req,res) { World.find(function (err,worlds) { if(err) { return handleError(res,err); } res.json(200,worlds); }); };
如果我切割数据,所以它不会被分块,那么json是很好的形成.我已经检查了mongo数据库,数据也可以在那里调试世界变量,我可以JSON.stringify并获得预期的字符串结果没有任何重复.但是在发送的那一刻,我正在收到json结果的反应.
更新评论
angle-fullstack 2.0.4
模式如下所示:
'use strict'; var mongoose = require('mongoose'),Schema = mongoose.Schema; var WorldSchema = new Schema({ name: String,info: String,active: Boolean,tiles: [Schema.Types.Mixed] }); module.exports = mongoose.model('World',WorldSchema);
种子:
var newWorld = new WorldModel({ _id: planet._objectId,name: "SimDD World",tiles : seed() }); newWorld.save(); ... var seed = function () { var data = []; for (var i = 0; i < planet.HEIGHT; i++) { for (var j = 0; j < planet.WIDTH; j++) { data.push({ coords:{ x:i,y:j },type:'.' }); } } return data; }
解决方法
今天关于javascript-使用JSON响应的数据表和js使用json对象的介绍到此结束,谢谢您的阅读,有关javascript – CodeIgniter – 如何从控制器返回Json响应、javascript – dc.js – 使用jquery data-table插件的数据表、javascript – IE iframe无法正确处理应用程序/ json响应、javascript – JSON响应中的重复块等更多相关知识的信息可以在本站进行查询。
本文标签: