dongwu3596 2012-09-30 16:27
浏览 75
已采纳

如何使用ajax发送带有输入类型图像的表单以防止重定向/重新加载

i have a question on the ajax request and how it would handle input type image. i have a list of images all displayed in a certain , i need the user to click on the image he or she wants and when this happens, it is added to their own customized list. the list is displayed at the bottom of the screen, which means that all the images they have chosen would appear at the bottom of the screen in their own box. so the concept is that i have a form, with inputs in the type of 'image'. here's the markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>userList</title>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<body>
//choose div containg all the images:
<div id="choose"><div id="inside">PICK AN IMAGE:<hr>
//the images will be loaded here in this form
<form type="" method="post" action="">
<input type="image" id="send" name="send" value="images/Woman-02-june.png" src="images/Woman-02-june.png"/>
<input type="image" id="send" name="send" value="images/Man-01-June.png" src="images/Man-01-June.png"/>
</form>
</div></div>
//list div that would display the images the user has chosen
<div id="list"><?php
if(file_exists("list.html") && filesize("list.html") > 0){
    $handle = fopen("list.html", "r");
    $contents = fread($handle, filesize("list.html"));
    fclose($handle);

    echo $contents;
}
?></div>
</body>
</html>

so when a user clicks on an image, it's suppossed to be sent to a script which writes the data sent into a file. the file is then loaded and displayed in the "list" . here's the script:

<?php
//get data from array
$pikc=$_POST['send'];
//open file to append
$fp=fopen("list.html", 'a');
//write data to file
fwrite($fp,  "<div class='msgln'>"."<img src=\"".$pikc."\">"."<br>"."</div>");
//close the file        
fclose($fp);


?>

as you can see, the data sent is the 'value' of the image clicked so that it is taken and concatenation is carried out to include it in the mark up for an image. i know that i need to use ajax to do this, so here is the ajax for it:

<script type="text/javascript" src="jquery-1.8.0.min (1).js"></script>
<script type="text/javascript">
$(document).ready(function(){
//If user submits the form
$("#send").click(function(){    
    var clientmsg = $("#send").val();
    $.post("post.php", {send: clientmsg});              

    return false;
});

});
</script>

i then include another function that enables auto-scrolling and constant showing of the 'list' i have no problem with that, it's working fine so i won't post it. the problem is, whenever i click on the first image, everything seems to be okay, data is sent to the script without any reloading,but whenever i click on the second one, i'm taken to the script page by my browser, although the file is updated with the content. how do i fix this, to stop any reloading or redirecting? please note that this is just a 'mock-test', the real thing will have data loaded from a mysql database, and that is why i've used the same id for bothimages. it will look something like this:

//after establishing mysql connection, loading data from database, etc
echo "<form method="post" action="">
//fetch array that is holding the loaded data
while ($row=mysql_fetch_array)
{
$row['img_path']=$image;    
//echo the data within the form
echo "<input id="send" type="image" value=\"".$image."\">"."<img src=\"".$image."\">";
}

echo "</form>"

so that all the image paths in the database are selected and the respsective images shown using them, there are over 300 of them. then, i'll need to send the form to the script via ajax and the same thing should happen as in my example.if the problem is with the id, i can't manually write id's for three hundred images!, i also don't think giving the form an id and then using it in the ajax process would be okay, i fear that no image would be sent, or all of them would be sent, unless i'm wrong). so, how do i fix this? thank you in advance, i am very new to programming, so i kindly ask for help. (please note that each user, in the real version will have their own "list" files and accounts). thanks, anything will be appreciated, even a different approach to accomplishing the same thing.

  • 写回答

1条回答 默认 最新

  • doubi2228 2012-09-30 22:07
    关注

    A couple things:

    On the surface, it looks like you've got a bit of divitis: the 2 <div>s around the <form> are probably not necessary (especially since they only encase one element—the form).

    You noted that you're aware you re-used the id send, and that it will change in actual implementation; however from the php you posted, it looks like multiple inputs with the same id will still be echo'd: this could cause many problems for your javascript (it might not do anything or it might produce unexpected results). What if instead of using id you used class="send"?

    <form id="choose" method="post">
        <input type="image" class="send" name="send[]" value="Woman-02-june.png" src="images/Woman-02-june.png" />
        <input type="image" class="send" name="send[]" value="Man-01-June.png" src="images/Man-01-June.png" />
    </form>
    

    And then when you need to reference them in jQuery, you can use $('#choose').find('.send'). Additionally, if you want the data of form elements to be part of a group, you can use name="send[]" to create an array: $_POST["send"] will be a numeric array (alternatively, you can make it an associative array like so: name="send[FOO]"—note that FOO should not be encased in quotes).

    However, grouping the inputs in this situation will be superfluous as the value of only one input will be submitted at a time. It would be applicable if you changed the form to allow a user selecting multiple images before submitting the form (use invisible checkboxes that are un/checked via jquery when a user un/clicks on an image). If you allow multiple selections before a submit, then you're AJAX will look something like this:

    $(function(){//short-hand for $(document).ready()
        $('#choose').submit(function(event){
            var form_data = $(this).serialize();
            $.post("post.php", {data:form_data}, function(){
                //stuff to do upon successful AJAX call
                var items;
                for ( var bio_img in form_data.send )
                    { items += '<li>'+bio_img+'</li>'; }
                //replace contents of <div id="list">
                //with the values of the input elements
                $('#list').html('<ul>'+items+'</ul>');
            });//$.post()
            event.preventDefault(); return false;//I double up just to be sure
        });//form submit
    });//document.ready
    

    Otherwise:

    $(function(){//short-hand for $(document).ready()
        $('#choose').submit(function(event){
            var form_data = $(this).serialize();//has data from only 1 input
            $.post("post.php", {data:form_data}, function(){
                //stuff to do upon successful AJAX call
                //assuming 'send' was not made an array in the input's name:
                //eg name="send" and not name="send[]"
                $('#list').find('ul').append('<li>'+form_data.send+'</li>');
            });//$.post()
            event.preventDefault(); return false;//I double up just to be sure
        });//form submit
    });//document.ready
    

    Lastly, it looks like you're using basic php mysql functions, which are not safe (see the warning message in the PHP documentation for mysql-fetch-array). You might consider PHP Data Objects (PDO)

    EDIT: From your question edit, it looks like you're worried about sending an image file via AJAX. However, there is no file upload input in your code; all a user is doing is selecting an option, and you already have the file (since you reference it via <input type="image" … src="…"). You're only sending the user's choice, not the image file itself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效