使用ajax更改div背景 - JQuery

时间:2011-06-05 08:34:30

标签: php jquery

我有一个html的网页,如下所示;

<head>
<script type="text/javascript" src="jquery-1.5.1.js"></script>
<style type="text/css">
#content{
  width: 200px;
  height: 200px;
  background-image: url(images/loader.gif);
  background-position: center;
  background-repeat: no-repeat;
  border: #3399FF solid 2px;
}
</style>
</head>
<body>
<div id="content">stringname</div>
</body>

我已将加载程序gif设置为其默认背景。我有一个php文件ajax.php,它返回一个$_POST["filename"]的数字(或名称)。我想要的是,页面在div(这里是stringname)内发送文本,而ajax将返回一个名称或数字。当脚本获取此数据时,后台网址可能会更改为return_data。jpg(此return_data是一个名称或数字)。

我认为后台更改脚本就像是;

var $cell = $('#content');
$cell.css('background-image', 'url(images/loader.gif)')

我该怎么做这个JQuery ??

提前致谢..

blasteralfred

3 个答案:

答案 0 :(得分:1)

<script type="text/javascript">
    $(document).ready(function(){
      $cell = $('#content');
      $.ajax({
        type: "POST",
        url: "ajax.php",
        data: { 
            filename: $("#content").html()
        },
        success: function(response){
                    alert(response);
            $cell.css("background-image", "url('/images/" + response + ".jpg')");
        }
      });
    });
</script>

并且不要忘记将jQuery脚本标记添加到-body-tag的底部(但仍在其中):

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

答案 1 :(得分:0)

$.ajax({
    ...ajax stuff...
    url : 'urlToYourPhpFile',
    data : {
        whateverTheHellYouWannaSendInAnObjectLiteralForm : true,
        floop : 'indeed'
    },
    type: 'POST, GET...',
    success: function(url) {
        ...your usual stuff
        $('#content').css('backgroundImage', url);
    }
});

http://api.jquery.com/jQuery.ajax/

答案 2 :(得分:0)

下面的JQuery假设ajax.php在div中返回你想要的内容。如果数据继续许多值,并且您只想在div中使用特定的值,比如标题,请考虑让ajax.php在其返回字符串上执行

json_encode()
。这将使得解析和处理javascript内容变得简单。

// Call this when you want to populate
$.get( 'ajax.php', function(data) {
    if( data ) {
        $("#content").html( data );
    }
} );