如何从json中获取值

时间:2011-08-18 17:14:01

标签: jquery json

我有一些jquery / ajax,它返回一些带有两个值的JSON。我不知道如何将这两个值放入变量中以用于输出。或者也许我可以使用它们而不将它们移动到变量?

jquery ajax声明:

$.ajax({
                                url: "proposemarriage_backend.php",
                                type: 'POST',
                                datatype: 'json',
                                data: 'wedding=' + firstweddingturn,

                                    success: function(result) {
                                        alert(result);
                                    }
                                }); // end ajax    

PHP后端:

$wedding1 = mysql_real_escape_string(filter_input(INPUT_POST,'wedding'));
if ($wedding1 > '0') {
list($season) = mysql_fetch_row(mysql_query("SELECT season FROM calendar WHERE calendar_ID=$wedding1",$db));
list($year) = mysql_fetch_row(mysql_query("SELECT year FROM calendar WHERE calendar_ID=$wedding1",$db));

$resultarray = array();

$resultarray[] = $season;
$resultarray[] = $year;

$resultjson = json_encode($resultarray);
echo $resultjson;

我最终得到的结果如“早春”,“71”。我想做一些像:

$('#div1').append('<br>The returned season is ' + season + ' and the year is ' + year + '.</br>')

2 个答案:

答案 0 :(得分:1)

对于第一个条目:

$('#div1').append('<br>The returned season is ' + result[0] + ' and the year is ' + result[1] + '.</br>');

循环以完成剩下的工作。但理想情况下,您应该更改PHP以将季节放在result[0][]中,将年份放在result[1][]中。或者更好,result['seasons']result['years']

编辑: 你有一个错字。将datatype更改为dataType。完成此操作后,jQuery将自动将JSON字符串解析为正确的对象结构。

答案 1 :(得分:0)

试试这个

$('#div1').append('<br>The returned season is ' + result[0] + ' and the year is ' + result[1] + '.</br>')