weixin_33725807 2013-02-01 08:17 采纳率: 0%
浏览 18

Ajax功能问题

I wrote an ajax function named getContent() and structured like this

getContent(whichcontent){//code here to get content}

The specific code is here:

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>");          
        }
    }
}

And I used the getContent like this

$(document).ready(function (){
    getContent(1,1);
    getContent(2,1);
}

The problem is I only get one ... and the other one with id page_2 doesn't appear. I'm wondering whether the ajax function can be only called once in a js function or I just made the ajax function wrong. Somebody help me!! Thanks in advance.

  • 写回答

2条回答 默认 最新

  • weixin_33735676 2013-02-01 08:25
    关注

    XMLHttpRequest calls are asyncronous, so if you use only one request object the second call to getContent will be ignored because receiveReq.readyState is neither 0 nor 4.

    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度