到目前为止,我一直在进行AJAX调用,用另一个页面替换div的内容,使用以下代码:
<script>
function fetchContainerContent(url, containerid) {
var req = false
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest()
} else {
return false
}
req.onreadystatechange = function() {
requestContainerContent(req, containerid)
}
req.open('GET', url, true)
req.send(null)
}
function requestContainerContent(req, containerid) {
if (req.readyState == 4 && (req.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML = req.responseText
}
</script>
我已经尝试将上面的代码转换为使用jQuery,但是它不起作用。换句话说,我试图模仿上述行为的最终结果,但它远不一样。事实上,屏幕上没有任何反应,没有任何变化。我应该提一下,我真的不需要加载......但是因为我见过的例子使用它,因为我不确定如何正确地学习jQuery,我把它留在了。
<script>
function fetchContainerContent(url, containerid) {
jQuery.ajaxSetup ({
cache: false
});
var ajax_load = "loading...' />";
jQuery("#load_basic").click(function() {
jQuery("#"+containerid).html(ajax_load).load(url);
});
}
</script>
提前致谢。我是jQuery的新手,所以我可能做了一些非常愚蠢的事情。
收到所有评论后(谢谢大家!)我只留下以下内容:
function fetchContainerContent(url, containerid){
var ajax_load = "loading...";
$("#load_basic").click(function(){$("#"+containerid).html(ajax_load).load(url);});
}
但我仍然遇到问题,因为它没有更新页面。没有js错误,没有任何反应。
答案 0 :(得分:2)
试试这个:
jQuery("#load_basic").click(function() {
jQuery("#result").html(ajax_load).load(url);
return false;
});
请注意点击处理程序末尾的return false
语句。如果load_basic
是按钮或锚元素,这将阻止传播click事件。
答案 1 :(得分:1)
我看到的唯一基本差异是:
"loading...' />"
。这闻起来不太好。"#result"
而不是使用"#" + containerid
对容器代码进行硬编码。click
事件,而不是(显然)在元素中内联。它原来是怎么样的?对于残余,代码看起来很好。
答案 2 :(得分:0)
问题是它没有调用你的回调方法吗?你必须回调.load方法。
<script>
function fetchContainerContent(url, containerid) {
jQuery.ajaxSetup ({
cache: false
});
var ajax_load = "loading...' />";
jQuery("#load_basic").click(function() {
jQuery("#result").html(ajax_load).load(url, null, requestContainerContent);
return false;
});
}
function requestContainerContent(responseText, textStatus, XMLHttpRequest) {
// do replacement in here
}
</script>
您必须在requestContainerContent中稍微调整一下代码,以便根据提供的参数执行所需的操作。
答案 3 :(得分:0)
好吧,即使我不太确定代码的质量,我似乎已经开始工作了。
var ajax_load = "loading...";
$("#"+containerid).html(ajax_load).load(url);