how to grab the values from json
I have some jquery/ajax which returns some JSON with two values. I do not know how to put those two values into variables to use in output. Or perhaps I can use them without moving them to variables?
jquery ajax statement:
$.ajax({
url: "proposemarriage_backend.php",
type: 'POST',
datatype: 'json',
开发者_JAVA百科 data: 'wedding=' + firstweddingturn,
success: function(result) {
alert(result);
}
}); // end ajax
PHP backend:
$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;
I end up with a result like "Early Spring", "71". And I want to do something like:
$('#div1').append('<br>The returned season is ' + season + ' and the year is ' + year + '.</br>')
For the first entries:
$('#div1').append('<br>The returned season is ' + result[0] + ' and the year is ' + result[1] + '.</br>');
Loop to get the rest. Ideally, though, you should change the PHP to put the seasons in result[0][]
and the years in result[1][]
. Or better yet, result['seasons']
and result['years']
.
EDIT:
You've got a typo. Change datatype
to dataType
. Once this is done, jQuery will automatically parse the JSON string to the right object structure.
Try this
$('#div1').append('<br>The returned season is ' + result[0] + ' and the year is ' + result[1] + '.</br>')
精彩评论