admin管理员组文章数量:1291103
I am passing the posts result of a query to JS so it can render the data in a select. Before I send out the result like this:
return new \WP_REST_Response( $return_data, 200 );
I checked the array in PHP an it yields the following, which is fine (sorted by name)
array(8) {
[1489]=>
string(3) "Gus"
[1499]=>
string(3) "Mia"
[1479]=>
string(4) "Odin"
[1488]=>
string(5) "Pablo"
[1490]=>
string(8) "Salvator"
[1491]=>
string(6) "Scooby"
[1492]=>
string(5) "Snowy"
[1485]=>
string(6) "Wesley"
}
In my JS, I have the following code:
this.request = $.ajax({
url: `${homeURL}/wp-json/mdr/v1/${animalType}`,
type: 'get',
dataType: 'json',
success: function (result) {
console.log(result);
Which prints the following:
Object {
1479: "Odin",
1485: "Wesley",
1488: "Pablo",
1489: "Gus",
1490: "Salvator",
1491: "Scooby",
1492: "Snowy",
1499: "Mia"
}
Why is the array converted to an object sorted by the ID instead of the order that I passed it from PHP?
I am passing the posts result of a query to JS so it can render the data in a select. Before I send out the result like this:
return new \WP_REST_Response( $return_data, 200 );
I checked the array in PHP an it yields the following, which is fine (sorted by name)
array(8) {
[1489]=>
string(3) "Gus"
[1499]=>
string(3) "Mia"
[1479]=>
string(4) "Odin"
[1488]=>
string(5) "Pablo"
[1490]=>
string(8) "Salvator"
[1491]=>
string(6) "Scooby"
[1492]=>
string(5) "Snowy"
[1485]=>
string(6) "Wesley"
}
In my JS, I have the following code:
this.request = $.ajax({
url: `${homeURL}/wp-json/mdr/v1/${animalType}`,
type: 'get',
dataType: 'json',
success: function (result) {
console.log(result);
Which prints the following:
Object {
1479: "Odin",
1485: "Wesley",
1488: "Pablo",
1489: "Gus",
1490: "Salvator",
1491: "Scooby",
1492: "Snowy",
1499: "Mia"
}
Why is the array converted to an object sorted by the ID instead of the order that I passed it from PHP?
Share Improve this question asked Jun 7, 2021 at 1:35 csaboriocsaborio 1122 silver badges13 bronze badges1 Answer
Reset to default 0Fix by using:
return new \WP_REST_Response( \json_encode( $return_data), 200 );
本文标签: javascriptWhy does my array sort order changes when I pass it to JS using WPRESTResponse
版权声明:本文标题:javascript - Why does my array sort order changes when I pass it to JS using WP_REST_Response? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741519730a2383109.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论