changing background color through Ajax jQuery?
scenario: my users have their own profile pages with different background colors and fonts, I want to retrieve the colors for example from a certain user using ajax. i.e.
$.ajax({
type: "POST",
data: "id",
url:开发者_开发百科 "ajax/css.php",
success: function (bg,font) {
$('#bg').css('background-color', 'bg');
$('#font').css('font-color', 'font');
}
ajax/css.php page
<?php
//retrieve the background and font data from database for the id(userID).
// this is the bit I'm stuck here, shall I echo the results or return them :~
?>
JSON would probably be easiest here, like this:
$.ajax({
type: "POST",
data: { id: someIDVariable },
url: "ajax/css.php",
success: function (result) {
$('#bg').css('background-color', result.bg);
$('#font').css('font-color', result.font);
}
});
Or a shorter form using $.getJSON()
is GET is an option:
$.getJSON("ajax/css.php", { id: someID }, function (result) {
$('#bg').css('background-color', result.bg);
$('#font').css('font-color', result.font);
});
Then in PHP:
eacho json_encode(array('font'=>$font,'bg'=>$bg));
//which will echo this format: { "font": "Arial", "bg": "#000000" }
Just make an action returning a valid JSON with the data you need. For instance if it returns:
{ color: "red", font:"arial"}
You can do:
$.post("user_css_info.json",{id:1234}, function(data){
alert("Color is" + data.color);
});
精彩评论