简体   繁体   English

从javascript数组中获取一个值

[英]Get one value from javascript array

I'm sure there's something stupid I am doing and the answer to this is very simple but all the searches I have done have dealt with looping over the array, I don't want that. 我确定我正在做一些愚蠢的事情,并且答案很简单,但是我所做的所有搜索都涉及循环遍历数组,我不希望这样。

I have an ajax call that is returning a response in the form of a very simple array. 我有一个ajax调用,它以非常简单的数组形式返回响应。 In the success function of my ajax call if I do this: 在我的ajax调用的成功函数中,如果执行以下操作:

console.log(response);

The array is logged to the console as expected. 阵列已按预期记录到控制台。 [0] => 100, [1] => 200 etc. [0] => 100,[1] => 200,依此类推。

If I try: 如果我尝试:

console.log(response[1]);

I am expecting to get 200 but it does nothing. 我期望得到200,但是它什么也没做。 I eventually want to insert the value into a redirect like this... 我最终想要将值插入到这样的重定向中...

window.location.replace('index.php?id=200');

But all I get is "index.php?id=" 但是我得到的只是“ index.php?id =“

Please someone put me out of my misery. 请有人使我摆脱痛苦。 What am I doing wrong? 我究竟做错了什么?

Edit: 编辑:

Changed the PHP to include the following: 将PHP更改为包括以下内容:

exit(json_encode("id"=>$id,"message"=>$message));

which returned an object (not a string). 它返回一个对象(不是字符串)。

Then in the success part of the ajax function: 然后在ajax函数的成功部分中:

success: function(response) {
window.location.replace('index.php?id=' + response.id + '&message=' + response.message);
}

This... for some reason, works fine. 这...出于某种原因,效果很好。 Don't ask me why. 不要问我为什么。

The easiest way of sending information to and from PHP/Javascript is with JSON. 与PHP / JavaScript之间来回发送信息的最简单方法是使用JSON。

In PHP you can use json_encode() to turn your array into a JSON string. 在PHP中,您可以使用json_encode()将数组转换为JSON字符串。 Then use JSON.parse() in Javascript to turn the string back into an object. 然后在Javascript中使用JSON.parse()将字符串转换回一个对象。

If you are using jQuery for the AJAX request and don't have the dataType set it will automagically detect it is JSON and parse it for you, this is probably why you didn't have to. 如果您对AJAX请求使用jQuery且未设置dataType ,它将自动检测它是JSON并为您解析,这可能就是您不必这样做的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM