I am trying to handle an array coming back from an ajax call. My current situation is a button gets clicked, and when clicked, it fires an ajax call. Here is a snippet of the PHP after ajax has been called..
我正在尝试处理从ajax调用返回的数组。我目前的情况是点击了一个按钮,当点击它时,它会触发一个ajax调用。这是ajax被调用后的PHP片段..
function count_total() {
$count = get_count();
if ($count == 0) {
$count = 1;
}
$total = get_total();
$response = array('count' => $count, 'total' => $total);
echo $response;
exit;
}
Ok so now this $response variable is passed back to the JS side and if I alert the variable obviously it will say "Array". So my question is, how can I work with this array? I am trying to get the key/value out?
好的,现在这个$ response变量被传递回JS端,如果我警告变量显然会说“Array”。所以我的问题是,我如何使用这个数组?我想要获得键/值?
Or I can't pass an array to it like that?
或者我不能像那样传递数组?
Any ideas?
有任何想法吗?
2 个解决方案
#1
0
change your echo to be this.
改变你的回声是这样的。
echo json_encode($response);
and then instead of alerting the response, parse it with a json parser library like this.
然后代替提醒响应,用这样的json解析器库解析它。
Then you will have a true javascript object not an array because you're using a associative array.
那么你将拥有一个真正的javascript对象而不是一个数组,因为你正在使用一个关联数组。
#2
0
PHP isn't sending back the array itself, just the word 'Array'. It can only send back plain text/HTML (or files if you mess with headers).
PHP不会发回数组本身,只是单词'Array'。它只能发回纯文本/ HTML(如果你搞乱标题,则发送文件)。
Look into either using JSON or an equivalent method that will take an array and put it into a text form to be recovered in JavaScript or roll your own.
查看使用JSON或等效方法,它将获取一个数组并将其放入文本形式,以便在JavaScript中恢复或滚动自己的数组。
For example you could echo "count=12;total=254" from PHP and use JavaScripts split() function to break it back into it's parts.
例如,您可以从PHP回显“count = 12; total = 254”,并使用JavaScripts split()函数将其分解为其部分。
#1
0
change your echo to be this.
改变你的回声是这样的。
echo json_encode($response);
and then instead of alerting the response, parse it with a json parser library like this.
然后代替提醒响应,用这样的json解析器库解析它。
Then you will have a true javascript object not an array because you're using a associative array.
那么你将拥有一个真正的javascript对象而不是一个数组,因为你正在使用一个关联数组。
#2
0
PHP isn't sending back the array itself, just the word 'Array'. It can only send back plain text/HTML (or files if you mess with headers).
PHP不会发回数组本身,只是单词'Array'。它只能发回纯文本/ HTML(如果你搞乱标题,则发送文件)。
Look into either using JSON or an equivalent method that will take an array and put it into a text form to be recovered in JavaScript or roll your own.
查看使用JSON或等效方法,它将获取一个数组并将其放入文本形式,以便在JavaScript中恢复或滚动自己的数组。
For example you could echo "count=12;total=254" from PHP and use JavaScripts split() function to break it back into it's parts.
例如,您可以从PHP回显“count = 12; total = 254”,并使用JavaScripts split()函数将其分解为其部分。