简体   繁体   English

使用ajax和PHP上传图像(预览不起作用)

[英]Image upload with ajax and PHP (preview not working)

I have the following HTML 我有以下HTML

<tr id="all_extended">
    <td id="portrait">
       <img id="image" <?if($image != NULL) echo "src='$image'"?>></img>
    </td>

and JAVASCRIPT JAVASCRIPT

$("#this_upload_is_working").ajaxForm({
                        target: '#image'
        }).submit();

But for some reason the image only appears if I refresh the page instead of instantly as it should. 但是由于某种原因,图像仅在我刷新页面时出现,而不是立即刷新。 Any idea on why? 知道为什么吗? And if so, any suggestion on how I can make it fadeIn with jquery? 如果是这样,关于如何使用jquery使其褪色的任何建议?

PHP is server side. PHP是服务器端。 Therefore, that is why this only works on refresh: 因此,这就是为什么仅在刷新时起作用的原因:

<?if($image != NULL) echo "src='$image'"?>

The above code has many errors as well, and should be written closer to this: 上面的代码也有很多错误,应该写得更近一些:

<?php if($image != NULL){echo "src='.$image.'";} ?>

You will have to do a couple things here; 您将不得不在这里做几件事;

1) Upon submission of the image, you will have to build a Javascript/jQuery function that sends the image to a PHP function that stores it on your server (You don't necessarily need to use a database to store the image, so long as you store the image URL in the database for referencing record ie yourwebsite.com/img.jpg). 1)提交图像后,您将必须构建一个Javascript / jQuery函数,将图像发送到将其存储在服务器上的PHP函数(不一定需要使用数据库来存储图像,因此当您将图像URL存储在数据库中以供参考记录时,即yourwebsite.com/img.jpg)。

2) The PHP script will then return the image URL where the image is stored. 2)然后,PHP脚本将返回存储图像的图像URL。

3) The client will then receive the URL where the image is stored, and you can populate your img src with the proper image URL, without refreshing the page. 3)然后,客户端将收到存储图像的URL,您可以使用正确的图像URL填充img src,而无需刷新页面。

I am trying to be a good attentive boyfriend to my girlfriend tonight, otherwise I would write example more scripts for you :( The good news is that with the outline of steps described above, you can learn and study enough to get really good at this type of programming! 我想今晚与我的女朋友成为一个细心的男朋友,否则我会为您编写更多脚本示例:(好消息是,通过上述步骤的概述,您可以学习和学习足够多的东西,从而真正做到这一点编程类型!

Cheers and keep on truckin'! 欢呼,继续努力! I hope this helps! 我希望这有帮助!

<img id="image" <?if($image != NULL) echo "src='$image'"?>></img>

Your code work after page refresh because image src populated from response value. 页面刷新后您的代码可以工作,因为图像src是从响应值填充的。

I guess your problem is instant image preview, if so then you can check this answer Preview an image before it is uploaded . 我想您的问题是即时图片预览,如果是这样,那么您可以检查此答案预览图片,然后再上传 If you browse any image you'll get the preview immediately. 如果您浏览任何图像,将立即获得预览。

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

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