jquery - 使用jquery ajax从数据库加载信息

标签 jquery ajax load

问题

我尝试使用以下内容

// Start method 1

var grbData = $.ajax({
        type : "GET",
        url : "http://grb.sonoma.edu:81/getgrbs.php",
        data : "start=0&perPage=3"}).responseText;

$("#ajaxDiv").html(grbData);

// End method 1

// Start method 2

$.get("getgrbs.php", { start : 0, perPage : 3},
        function(data) {
              $("#tst").html(data);
        }, "html");

// End method 2

在此页面上:http://grb.sonoma.edu:81/paging.php从数据库加载数据。方法 1 似乎仅在 IE8 中有效,但仅在页面刷新后有效。首次加载页面时,我收到“完成此操作所需的数据尚不可用”。错误。

我更喜欢方法 1 的原因是它使我能够访问表中的各个行。例如。每行都有一个类“爆”。我正在使用

$(".burst").click(function() {
        $(".burst").css("background-color", "");
        $(this).css("background-color", "yellow");
    });

单击时更改所选行的颜色。这似乎仅适用于方法 1,不适用于方法 2。

以上所有代码都封装在$(document).ready()中。我已经尝试过

$("#ajaxDiv").load("getgrbs.php", { start : 0, perPage : 3});

但我得到的结果与方法 2 类似。

如何让点击功能与方法 2 一起使用或让方法 1 在所有浏览器上工作而无需刷新?感谢您为此提供的任何帮助。

我需要在 ajax 中执行此操作(尝试过不使用 jquery 的 ajax,但也没有运气),因为页面上的其他内容不会随着用户翻页数据而改变。

解决方案附录(答案中有更好的解决方案)

成功使用“成功”后,我注意到单击行并更改背景颜色的功能消失了。所以我做了以下操作,这似乎有效。不确定这是否是最好的方法。

var grbData = $.ajax({
    type : "GET",
    url : "http://grb.sonoma.edu:81/getgrbs.php",
    data : "start=0&perPage=3",
    dataType : 'html',
    success: function (data) {
            $("#ajaxDiv").replaceWith(data);
            startInteraction();
        }
});

function startInteraction() {
    $(".burst").click(function() {
        $(".burst").css("background-color", "");
        $(this).css("background-color", "yellow");
    });
}

最佳答案

尝试:

var grbData = $.ajax({
        type : "GET",
        url : "http://grb.sonoma.edu:81/getgrbs.php",
        data : "start=0&perPage=3",
        success: function (html) {
            $("#ajaxDiv").html(html);
        }
});

它不起作用的原因是它在加载完成之前尝试使用您的 html。代码的执行速度比返回结果的速度快。

要保留您的点击事件,您可以使用 .live,这样它将为将来添加到页面的元素触发该事件,就像您的 ajax 代码一样。

$(document).ready( function () {
    $(".burst").live('click',function() {
        $(".burst").css("background-color", "");
        $(this).css("background-color", "yellow");
    });
});

关于jquery - 使用jquery ajax从数据库加载信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1313813/

相关文章:

javascript - 错误 - 未捕获类型错误 : Cannot set property 'innerHTML' of undefined

asp.net - 如何在jquery ajax调用中消费webservice的返回值?

ajax - ajax 调用后渲染 'like' 按钮

r - Microsoft Azure ML 中的插入符包

c# - 单击 asp 按钮获取下拉列表的值

javascript - 在 Javascript/jQuery 中解析 PHP 序列化数组

ios - 加载大文本文件的替代方案 - Swift

c# - 在C#winform中加载用户控件时,将焦点放在文本框中

jquery Flexslider 手动控件不起作用

javascript - jQuery Accordion 菜单动画摆动