简体   繁体   English

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

[英]Ajax request loads entire page in div when it's not supposed to

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. 但是,我的ajax代码不配合。 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. 现在,真正奇怪的是,当我在本地计算机上尝试运行时,它可以正常运行,但在实际的Web服务器上却无法运行。

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: 和我的PHP文件:

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. 在此页面http://bit.ly/dXrGY6中 ,使用相对路径都可以正常工作。 Replacing it with an absolute path like "http://www..." or "../test/....." makes it malfunction again. 用绝对路径(例如“ http:// www ...”或“ ../ test / .....”)替换它会使它再次出现故障。 I am using absolute paths in another section of my site and it works fine: http://bit.ly/fCmmjy . 我在网站的另一部分中使用绝对路径,并且工作正常: http : //bit.ly/fCmmjy I dont know why it doesn't work here... 我不知道为什么它在这里不起作用...

I can't figure out what is wrong. 我不知道怎么了。 Any ideas? 有任何想法吗?

are you sure your php code is not spitting out anymore html? 您确定您的php代码不再随地吐出html吗? try adding a die 尝试添加die

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM