doudizhu2222 2010-12-20 02:35
浏览 40

Ajax请求在div不应该加载整个页面

I am trying to do something very simple, a user clicks a link and a mini-form with a file upload input appears somewhere below it.

However, my ajax code is not cooperating. Instead, it loads the entire current (i think) page. I had this issue again some time ago and i managed to fix it, however for the life of me i can't remember how i did it.

Now the really strange thing is that when i try it on my local computer it works fine, but on the actual web server it doesn't.

Code:

function ajaxRequest(targetUri, parameters, cbFunction){

if(window.XMLHttpRequest){
    request = new XMLHttpRequest();
  }else{
    request = new ActiveXObject("Microsoft.XMLHTTP");
  }


  request.onreadystatechange = cbFunction;
  request.open("POST", targetUri, true);
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send(parameters);

   }

function addImage(){
  parameters = "action=ajaxRequest";
  ajaxRequest("http://www.mysite.com/gallery/addImage.php", parameters, function(){
    if((request.readyState == 4) && (request.status == 200)){
   document.getElementById("formContainer").innerHTML = request.responseText;
    }
  });

}

And my PHP file:

function addImage(){
  echo '
 <div class="mainBlockBody">
   <form action="index.php" method="post" enctype="multipart/form-data">
  <input type="hidden" name="galleryAction" value="addImage" />
  <input type="file" name="upFile" />
  <input type="submit" value="Submit" />
   </form>
 </div>
  ';
}

if($_POST['action'] == 'ajaxRequest'){
  addImage();
}

Link & placeholder:

<a href="javascript:addImage()">Add Image</a>
<div id="formContainer"></div>

Any help is much appreciated!

EDIT:

I think i have narrowed down the problem to the... path. In this page http://bit.ly/dXrGY6 it all works fine, using a relative path. Replacing it with an absolute path like "http://www..." or "../test/....." makes it malfunction again. I am using absolute paths in another section of my site and it works fine: http://bit.ly/fCmmjy . I dont know why it doesn't work here...

I can't figure out what is wrong. Any ideas?

  • 写回答

1条回答 默认 最新

  • doutangguan2460 2010-12-20 02:53
    关注

    are you sure your php code is not spitting out anymore html? try adding a die

    if($_POST['action'] == 'ajaxRequest'){
      addImage();
      die();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c