Order-safe value passing from php to javascript

时间:2021-01-08 17:03:53

If I pass an array from php to js:

如果我将数组从php传递给js:

 var array = <?php echo json_encode($array); ?>;

Is it true that the ith element js array and the php array will refer to the same data?

是的,第i个元素js数组和php数组会引用相同的数据吗?

2 个解决方案

#1


1  

I believe the answer is yes for index-based arrays. On associative arrays, that translate to js objects, what json_encode does doesn't really matter, as JavaScript does not guarantee any particular key order when iterating over the keys (with for..in).

我相信对于基于索引的数组,答案是肯定的。在转换为js对象的关联数组中,json_encode的作用并不重要,因为JavaScript在迭代键时不保证任何特定的键顺序(使用for..in)。

#2


1  

what are you trying here? mixing php and js?

你在这尝试什么?混合php和js?

You should use the function's parameter you pass: e.

您应该使用您传递的函数参数:e。

var someArray = <?php echo json_encode($array); ?>;

for(var i = 0; i < someArray.length; i++) {
    infoWindow.setContent(createDivForElement(someArray[i]) );
}

function createDivForElement(e) {
    var result = '<div>';
    result += '<img src=' + e.thumbail + '/>'; 
    result += '</div>'
    return result;
}

You already pass someArray[i], you can address inside of the function with e. Then you don't need to involve any PHP in the function. You only need PHP here to pass the data to JS.

你已经传递了someArray [i],你可以用e来解决函数内部的问题。然后你不需要在函数中涉及任何PHP。你这里只需要PHP将数据传递给JS。


Always keep in mind that once you put PHP somewhere in, it won't change on the client-side.

请记住,一旦将PHP放入某处,它就不会在客户端发生变化。

#1


1  

I believe the answer is yes for index-based arrays. On associative arrays, that translate to js objects, what json_encode does doesn't really matter, as JavaScript does not guarantee any particular key order when iterating over the keys (with for..in).

我相信对于基于索引的数组,答案是肯定的。在转换为js对象的关联数组中,json_encode的作用并不重要,因为JavaScript在迭代键时不保证任何特定的键顺序(使用for..in)。

#2


1  

what are you trying here? mixing php and js?

你在这尝试什么?混合php和js?

You should use the function's parameter you pass: e.

您应该使用您传递的函数参数:e。

var someArray = <?php echo json_encode($array); ?>;

for(var i = 0; i < someArray.length; i++) {
    infoWindow.setContent(createDivForElement(someArray[i]) );
}

function createDivForElement(e) {
    var result = '<div>';
    result += '<img src=' + e.thumbail + '/>'; 
    result += '</div>'
    return result;
}

You already pass someArray[i], you can address inside of the function with e. Then you don't need to involve any PHP in the function. You only need PHP here to pass the data to JS.

你已经传递了someArray [i],你可以用e来解决函数内部的问题。然后你不需要在函数中涉及任何PHP。你这里只需要PHP将数据传递给JS。


Always keep in mind that once you put PHP somewhere in, it won't change on the client-side.

请记住,一旦将PHP放入某处,它就不会在客户端发生变化。