通过Ajax jQuery改变背景颜色?

时间:2010-12-02 11:45:36

标签: php javascript jquery css ajax

场景:我的用户拥有自己的不同背景颜色和字体的个人资料页面,我想要使用ajax从某个用户检索颜色。即。

$.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页面

<?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 :~

?>

2 个答案:

答案 0 :(得分:4)

JSON在这里可能最简单,就像这样:

$.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);
   } 
});

或者使用$.getJSON()的简短形式是GET是一个选项:

$.getJSON("ajax/css.php", { id: someID }, function (result) { 
  $('#bg').css('background-color', result.bg);
  $('#font').css('font-color', result.font);
});

然后在PHP中:

eacho json_encode(array('font'=>$font,'bg'=>$bg));
//which will echo this format: { "font": "Arial", "bg": "#000000" }

答案 1 :(得分:0)

只需执行操作即可返回包含所需数据的有效JSON。例如,如果它返回:

{ color: "red", font:"arial"}

你可以这样做:

$.post("user_css_info.json",{id:1234}, function(data){
  alert("Color is" + data.color); 
});