Home  >  Article  >  Web Front-end  >  Upload files without refreshing and return custom values

Upload files without refreshing and return custom values

PHPz
PHPzOriginal
2016-05-16 15:55:401218browse

This article briefly shares with you the methods and examples of how to solve the problem of uploading files without refreshing in personal projects. Friends in need can refer to it.

I encountered such a problem during the development process today: Excel needs to be uploaded to the server for parsing, but when the document is inappropriate, I hope that the page will not be refreshed to prompt the user that the document is inappropriate. After thinking hard for a long time, I found a lot of information on the Internet and finally succeeded in the experiment. I will share the processing method here:

First of all, let me talk about the processing idea: add a hidden iframe to the page and set the target attribute of the form. Set to the id of the iframe, so that when the form is submitted, the excel file will be transmitted to the background in the form of a file stream. Custom operations can be performed after receiving it in the background. The information returned will be displayed in the iframe without jumping. Before the iframe Set to hidden, so the page will not change. Then we need to monitor changes in the iframe content, and then pass the content to the JS method in the main window for the next step of custom processing.

The page code is as follows:

<form id="input" action="importExcel.jhtml" method="post" enctype="multipart/form-data" target="hiddenIFrame">
  <input id="excelFile" name="file" type="file" />
  <input type="submit" class="button" value="导入excel"/>
</form>
<iframe id=&#39;hiddenIFrame&#39; name=&#39;hiddenIFrame&#39; style="display:none;"></iframe>

The JS code is as follows (jqeury needs to be introduced):

$(function(){
  $("#hiddenIFrame").load(function(){
    var wnd = this.contentWindow;
    var str = $(wnd.document.body).html();
    callback(str);
  });
})
 
function callback(info){
  alert(info);
}

The background code will not be introduced in detail. Just like traditional submission, the background will obtain a file stream with the same name based on the name value of the input component (for example, the name of the input component in the page code above is file, then the background received It is a file stream named file), and you can perform customized operations after receiving it.

For more related tutorials, please visit JavaScript Tutorial

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn