This is what I am currently doing to trim all of my value. It is ugly and a too repetitive.
这是我目前正在做的,以削减我所有的价值。它很丑,而且太重复了。
var strHTML = '';
$.getJSON('info.php',
function(data) {
$.each(data, function(i, item) {
strHTML += $.trim(item.fname) +
$.trim(item.lname) +
$.trim(item.address) +
$.trim(item.phone) +
...(about 10 more of these);
});
});
There ought to be a better way to do this.
应该有更好的方法来做这件事。
3 个解决方案
#1
1
A for...in
example, with hasOwnProperty
:
一个……在示例中,hasOwnProperty:
var obj = {
foo: ' bar',
blahblah: ' ahahaha '
};
var arr = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push($.trim(obj[key]));
}
}
alert(arr.join(','));
#2
1
I'd say you should trim the data on the PHP-side, as it's your PHP script that generates it 1.
我建议您应该在PHP端修改数据,因为生成它的是PHP脚本1。
Basically : make sure your info.php
script generates correct data.
基本上:确保你的信息。php脚本生成正确的数据。
In PHP, you can use the trim()
function.
在PHP中,可以使用trim()函数。
And if your data is stored in an array, you can apply that function to all items of that array using the array_map()
function :
如果数据存储在数组中,可以使用array_map()函数将该函数应用到该数组的所有项:
$data = array_map('trim', $data);
As a consequence, I will add the PHP tag to this question
因此,我将向这个问题添加PHP标记
#3
0
If you want all properties of item to be trimmed you can use the for (props in item) {} -loop to loop through all of them. Because u can use this on all javascript-object you can create a function that does the trimming on all properties of an object.
如果您想要对项目的所有属性进行调整,可以使用for(道具in item) {} -loop循环遍历所有属性。因为u可以在所有javascript对象上使用它,所以可以创建一个函数来对对象的所有属性进行微调。
#1
1
A for...in
example, with hasOwnProperty
:
一个……在示例中,hasOwnProperty:
var obj = {
foo: ' bar',
blahblah: ' ahahaha '
};
var arr = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push($.trim(obj[key]));
}
}
alert(arr.join(','));
#2
1
I'd say you should trim the data on the PHP-side, as it's your PHP script that generates it 1.
我建议您应该在PHP端修改数据,因为生成它的是PHP脚本1。
Basically : make sure your info.php
script generates correct data.
基本上:确保你的信息。php脚本生成正确的数据。
In PHP, you can use the trim()
function.
在PHP中,可以使用trim()函数。
And if your data is stored in an array, you can apply that function to all items of that array using the array_map()
function :
如果数据存储在数组中,可以使用array_map()函数将该函数应用到该数组的所有项:
$data = array_map('trim', $data);
As a consequence, I will add the PHP tag to this question
因此,我将向这个问题添加PHP标记
#3
0
If you want all properties of item to be trimmed you can use the for (props in item) {} -loop to loop through all of them. Because u can use this on all javascript-object you can create a function that does the trimming on all properties of an object.
如果您想要对项目的所有属性进行调整,可以使用for(道具in item) {} -loop循环遍历所有属性。因为u可以在所有javascript对象上使用它,所以可以创建一个函数来对对象的所有属性进行微调。