gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:57:00 25 4
gpt4 key购买 nike

问题

我尝试使用以下内容

// 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com