简体   繁体   中英

PHP Array to jQuery array with JSON. ($.post, parseJSON, json_encode)

I am trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array . I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:

The PHP code:

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
echo json_encode($arr); 

The jQuery code:

$.post("dbFile.php", str, function(theResponse){
     alert('the response: ' + theResponse);
     var obj = $.parseJSON(theResponse);
     alert(obj.a);

I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:

$arr[$i] = mysqlresults ... $i++;

So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?

Use the array access syntax:

alert(obj[42]);

You can use:

alert(obj['a']);

See this question for more info.

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.

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