我写了一个名为getContent()的ajax函数,结构如下
getContent(whichcontent){//此处代码获取内容}
具体代码如下:
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); //Not IE
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
} else {
alert("Your browser doesn't support the XmlHttpRequest object. Better upgrade to Firefox.");
}
}
var receiveReq = getXmlHttpRequestObject();
var page_id = 1;
function getContent(which_page,append){
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'spt/page_'+which_page, true);//get the text file
receiveReq.onreadystatechange = function(){
handleGetContent(which_page,append);
}
receiveReq.send(null);
}
}
function handleGetContent(which_page,append){
if (receiveReq.readyState == 4) {
if(append == 1){
$('#container').append("<div class='page' id='page_"+which_page+"'><div class='title'>围城</div><p>" + receiveReq.responseText + "</p><div class='pagenum'>"+which_page+"</div></div>");
}
if(append == 0){
$('#container').prepend("<div class='page' id='page_"+which_page+"'><div class='title'>围城</div><p>" + receiveReq.responseText + "</p><div class='pagenum'>"+which_page+"</div></div>");
}
}
}
我使用了像这样的getContent
$(document).ready(function (){
getContent(1,1);
getContent(2,1);
}
问题是我只得到一个......并且没有出现另一个带有id page_2的人。我想知道ajax函数是否只能在js函数中调用一次,或者我只是使ajax函数错误。来人帮帮我!!提前谢谢。
答案 0 :(得分:0)
XMLHttpRequest调用是异步的,因此如果您只使用一个请求对象,则会忽略对getContent
的第二次调用,因为receiveReq.readyState
既不是0也不是4。
答案 1 :(得分:0)
我认为代码没问题,但如果您对ajax有疑问,那么您可以使用jquery
,如果没有,那么您可以使用ajax的单个函数,例如:http://www.w3schools.com/ajax/ajax_aspphp.asp
或尝试此代码
// change the function like
function getContent(which_page,append){
var receiveReq = getXmlHttpRequestObject();// Create object here
receiveReq.open("GET", 'spt/page_'+which_page+'.txt', true);//get the text file
//write the extension of the file
receiveReq.onreadystatechange = function(){
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
handleGetContent(receiveReq,which_page,append);
}
}
receiveReq.send(null);
}
// add an extra parameter in this function
function handleGetContent(receiveReq,which_page,append){
if (receiveReq.readyState == 4) {
if(append == 1){
$('#container').append("<div class='page' id='page_"+which_page+"'><div class='title'>围城</div><p>" + receiveReq.responseText + "</p><div class='pagenum'>"+which_page+"</div></div>");
}
if(append == 0){
$('#container').prepend("<div class='page' id='page_"+which_page+"'><div class='title'>围城</div><p>" + receiveReq.responseText + "</p><div class='pagenum'>"+which_page+"</div></div>");
}
}
}
$(document).ready(function (){
getContent(1,1);
getContent(2,1);
});// change this line also