PHP数组到带有JSON的jQuery数组. ($ .post,parseJSON,json_encode) [英] PHP Array to jQuery array with JSON. ($.post, parseJSON, json_encode)
问题描述
我正在尝试获取一个php文件设置,以从jQuery AJAX调用返回MySQL数据库查询的结果.返回的结果将是一个数组.我有一个非常基本的开始,我只是在php文件中来回获取一些基本数据,但是遇到了一些基本的语法问题:
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:
PHP代码:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
jQuery代码:
$.post("dbFile.php", str, function(theResponse){
alert('the response: ' + theResponse);
var obj = $.parseJSON(theResponse);
alert(obj.a);
我可以打印出obj.a,obj.b,obj.c ...没问题.问题是当我通过MySQL结果增加时,我将增加一个计数器.因此,该数组不使用字母,它使用数字:
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++;
因此,在JavaScript/jQuery中,我有一个对象(而不是数组).例如,我可以打印出obj.a,但不能打印出obj.2(例如).换句话说,如果我用php数组中的数字替换字母,我不知道如何在JavaScript/jQuery中将它们打印出来.我可以将parseJSON返回的对象以某种方式更改为数组(以便可以循环遍历它)吗?
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)?
推荐答案
您可以使用:
alert(obj['a']);
有关更多信息,请参见此问题.
See this question for more info.
这篇关于PHP数组到带有JSON的jQuery数组. ($ .post,parseJSON,json_encode)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!