I've searched through the site and can't see a question quite like mine so I hope this isn't a copy.
So I've got a PHP script which is supposed to return a JSON array to my AJAX, and I want to use the array to generate a URL.
However, even though I'm pretty sure I've got an array on the PHP end, when I json_encode I'm getting a simple string out on the other end.
PHP Code:
$n = 10;
$all_titles = array();
while($row = mysqli_fetch_array($result)) {
$title = trim($row['Job Title']);
if(array_key_exists($title, $all_titles)) {
++$all_titles[$title];
} else {
$all_titles[$title] = 1;
}
}
arsort($all_titles);
$top_titles = array_slice($all_titles, 0, $n);
$title_list = array();
foreach (array_values($top_titles) as $key => $val) {
array_push($title_list, array_keys($top_titles)[$key]);
}
echo json_encode($title_list);
These array operations seem to be working so far, based on other tests I've done, so I'm pretty sure that $title_list is an array.
Here is my JS:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert("Generated URL: " + URL_gen(xmlhttp.responseText));
}
}
And finally where the problem arises:
function URL_gen(list) {
var url = list[2];
return url;
}
I have varied the number in list[#] (list[0], list[1], etc.) and each one is a character, meaning list (which is passed in from onreadystatechange as the responsetext from the PHP function above) is a string, not a JSON array.
Any suggestions?
That's what it does. Returns a string. You need to parse it on the client side.
alert("Generated URL: " + URL_gen(JSON.parse(xmlhttp.responseText)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.