【问题标题】:how to html form post - file uploading and reading json response from php server如何 html 表单后文件上传和从 php 服务器读取 json 响应
【发布时间】:2014-11-21 01:28:10
【问题描述】:

我正在尝试将文件上传到 php 我的 server.file 并通过多部分 /form-data 上传数据,在 php 服务器上接收到的文件和数据但在我的 php 服务器中返回 json 响应。请帮助我如何读取 json 响应在我的网页中,如果它的成功(代码 = 0)意味着它重定向另一个页面。php服务器对于android和网页都很常见。json响应看起来像{“code”:0,“message”:“success”}

<div style="height:0px;overflow:hidden">
    <form id="myForm" action="http://192.168.2.4/digiid/api/addid" 
        method="post" enctype="multipart/form-data" runat="server">

        <input type="file" name="file" id="file" onchange="showMyImage(this)" />
        <input type="hidden" name="userid" value="<?php echo $_SESSION["userid"]?>">
        <input type="hidden" id="inputfilename" name="filename" value="here">
    </form>
</div>

<a class="button1" id="browseButton" onclick=""  style="width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Select ID</font></a>
<br/>

<div>

            <img src='images/capture_picture_size.png' id='imgscreen'  width='200' height='200'>

<br/>


<p id="filename" style="color: #ffffff; font-size: 20px" >
    Title of the ID<br/></p>

<a class="button1"onclick="myFunction()" style= " width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Save ID</font></a></form>

</div>  

<script>
    function myFunction() {
       document.getElementById("myForm").submit();
    }
</script>

<script>
    browseButton.onclick=function chooseFile() {
        document.getElementById("file").click(); 
    };

    function showMyImage(fileInput) {

        var files = fileInput.files;

        var file = files[0];
        var imageType = /image.*/;

        var img=document.getElementById("imgscreen");
        var reader = new FileReader();
        reader.onload = (function(aImg) {
            return function(e) {
            //x=e.target.result

            img.src = e.target.result;
            var extfilename=file.name;
            document.getElementById("filename").innerHTML=extfilename.slice(0,-5) ;

            document.getElementById("inputfilename").value=extfilename.slice(0,-5);
     };
 })(img);

 reader.readAsDataURL(file);

 }</script>

【问题讨论】:

  • json 响应是什么样的?
  • json 响应看起来像 {"code":0,"message":"success"}
  • 您能重新格式化您的代码吗?为什么您尝试访问 $_POST['photo'] ?您的表单中没有这样的输入。使用 $_FILE 而不是 $_POST 访问文件上传
  • 发布您的php 服务器端代码

标签: javascript php jquery html json


【解决方案1】:

我认为它应该适合你。像我一样使用 AJAX

     //Your php code
        $arrToJSON = array(
        "dataPHPtoJs"=>"yourData",
        "asYouWant"=>"<div class=\".class1\">soemting</div>"    
        );  
        return json_encode(array($arrToJSON));




    //Your javaScript code
    $(document).on("event", "#idElement", function(){
        //Data you want to send to php evaluate
         var dt={ 
                  ObjEvn:"btn_Login",
                  dataJsToPHP: $("#txt_EmailLogin").val()
                };

        //Ajax      
         var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
                                url: "yourServer.php",
                                type: "POST",
                                data: dt,
                                dataType: "json"
                            });

        //Ajax Done catch JSON from PHP 
            request.done(function(dataset){
                for (var index in dataset){ 
                     dataPHPtoJsJS=dataset[index].dataPHPtoJs;
                     asManyasYouWantJS=dataset[index].asYouWant;
                 }

                 //JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response
                 if(dataPHPtoJsJS){
                    $( "#idYourHtmlElement" ).removeClass( "class1" )
                    $( "#idYourHtmlElement" ).addClass( "class2" )
                 }


         }); 

        //Ajax Fail 
            request.fail(function(jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }); 
    }

【讨论】:

    【解决方案2】:

    您可能应该使用 AJAX 调用。这是一个使用 jQuery 的解决方案:

    <script type="text/javascript">
    $(document).ready(function(){
        $("#browseButton").click(function(){
            var url = "";
            var formdata = $("#myForm").serialize();
            $.ajax({
                url: url,
                type: 'POST',
                data:  formdata,
                dataType: 'json',
                cache: false,
                contentType: false,
                processData: false,
                success: function(response){
                    if(response.status == "success"){
                        // Success
    
                    } else {
                        // Failure
    
                    }
                },
                error: function(response){
                    // Error
    
                }          
            });
        });
    });
    </script>
    

    为了重定向用户,你可以使用:window.location.href = " ... your_url ...";

    这里解释一下如何使用jQuery AJAX和多部分数据:

    Sending multipart/formdata with jQuery.ajax

    【讨论】:

      【解决方案3】:

      试试json_decode

          $data = ({"code":0, "message":"success"});
          $array = json_decode($data, true);
      

      通过将第二个参数传递给 true,您将得到数组而不是对象的响应。

      然后将按如下方式填充数组:

          array (size=2)
          'code' => int 0
          'message' => string 'success' (length=7)
      

      【讨论】:

        【解决方案4】:

        您的 JSON 响应将是 php.ini 中的一种关联数组。 使用“json_encode”将您的数组数据编码为 JSON 并根据需要返回值。

           $arr = array('status' => $status, 'status2' => $status2, );
           echo json_encode($arr);
        

        注意:如果您使用 ajax 调用 php 文件,则不要在该文件中使用任何 php echo/print,甚至不要使用 HTML。仅 ECHO “json_encode();”没有其他的。

        【讨论】:

          【解决方案5】:

          总结一下:

          1. 使用带有native JS (>=IE10) 或jQuery 的AJAX 将您的数据上传到服务器
          2. Catch(native JS 中的 xhr.responseText)和parse the response
          3. 使用 window.location.href="success.php" 重定向

          【讨论】:

            猜你喜欢
            • 2014-11-03
            • 2014-10-20
            • 1970-01-01
            • 2012-12-07
            • 2015-10-24
            • 1970-01-01
            • 2012-04-03
            • 2012-09-08
            • 2016-05-30
            相关资源
            最近更新 更多