如何在同一个div中填充响应,该div被填充为ajax

时间:2011-09-12 22:28:02

标签: javascript html ajax

我有一个HTML页面

说main.php,它使用ajax在div中填充“upload.php”。

现在在这个upload.php中,我上传了一个图片,我想以某种方式,在main.php中创建这个div,向我展示图像加载成功与否的响应。

我的代码如下所示:

main.php

<script type="text/javascript">
function showHint()
{
    var str = document.form1.filenumber.value;
    if (str.length==0)
      { 
      document.getElementById("txtHint").innerHTML="";
      return;
      }
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","upload.php?filenumber="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>

<form name="form1" >    
    <tr>
        <td>File Number </td><td><input type="text" id="11" name="filenumber" /></td>

</form>
        <td colspan="2"><input type="submit" onclick='showHint()'></td>
    </tr>   

</table>
<div id="txtHint"></div>

上传.php

<?php   
$filenumber = clean($_GET['filenumber']);

if($filenumber != '') {
    $qry = "SELECT * FROM profile WHERE filenum='$filenumber'";
    $result = mysql_query($qry)
    or die(mysql_error());  
    $row = mysql_fetch_array( $result );



    if($result) {
        if(mysql_num_rows($result) == 0) {
            $errmsg = '<div style="width:300px; height:100px;color:red;margin:0px auto;position:relative;top: 30%">No such record found. Redirecting back to the status page. </p>';
            $errflag = true;
        }   
        else
        {
        ?>      

            <form enctype="multipart/form-data" action="uploader.php" method="POST">
             Please choose a file: <input name="uploaded" type="file" /><br />
             <input type="submit" value="Upload" />
             </form> 

        <?php
        }
        //@mysql_free_result($result);
    }
    else {
        die("Query111 failed");
    }
}
?>

upload.php调用uploader.php,我想在同一个div中显示其响应

    <?php 
    $target = "images/"; 
    $target = $target . basename( $_FILES['uploaded']['name']) ; 
    $ok=1; 
    if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
    {
        echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
    } 
    else {
        echo "Sorry, there was a problem uploading your file.";
 }
 ?> 

欢迎您提出建议,感谢您的帮助。

由于 Zee的

1 个答案:

答案 0 :(得分:1)

正如GolezTrol所提到的,您应该考虑使用JQuery,这样可以更轻松地使用AJAX。

要回答您的问题,您可以使用JSON encoded response分隔有关上传过程结果的信息以及您希望填充div的实际结果。