如何从php服务器上传和读取json响应的html表单post文件

时间:2022-10-16 12:53:39

i am trying file uploading to php my server.file and data uploading through multi part /form-data ,the file and data received on php server but in my php server return json response .please help me how to read json response in my webpage and if its success(code=0) means it redirect another page .the php sever is common for both android and web pages .json response look like {"code":0,"message":"success"}

我正在尝试上传文件到php我的服务器。通过多声部/格式文件和数据上传,php服务器上接收到的文件和数据但我的php服务器返回json响应,请帮助我如何在我的网页读取json响应,如果它的成功(代码= 0)意味着它另一个页面重定向,php服务器是常见的android和网页. json响应看起来像{“代码”:0,“消息”:“成功”}

<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>

5 个解决方案

#1


5  

I think it should work for you. Using AJAX, as I do

我想它应该适合你。使用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


2  

You should probably use an AJAX call. Here's a solution using jQuery:

您可能应该使用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>

In order to redirect the user, you can use: window.location.href = " ... your_url ...";

要重定向用户,可以使用:windows .location。href = "……your_url…”;

Here's an explanation on how to use jQuery AJAX and multi-part data:

下面是如何使用jQuery AJAX和多部分数据的说明:

Sending multipart/formdata with jQuery.ajax

发送多部分/ formdata jQuery.ajax

#3


1  

try json_decode.

json_decode试试。

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

by passing 2nd parameter to true you will get response in array instead of object.

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

the array will be then populated as follow:

数组将被填充如下:

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

#4


1  

Your JSON response would be a kind of associative array in php. Encode your array data into JSON using "json_encode" and return values as you want .

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

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

NOTE: If you are using ajax to call php file then do not use any php echo/print in that file and not even HTML. ECHO only "json_encode();" Nothing else.

注意:如果使用ajax调用php文件,那么不要在该文件中使用任何php回显/打印,甚至不要使用HTML。回声只有“json_encode();”什么都没有。

#5


1  

To sum it up:

总结一下:

  1. Upload your data to server using AJAX with native JS (>=IE10) or jQuery
  2. 使用本地JS (>=IE10)或jQuery将数据上载到服务器
  3. Catch (xhr.responseText in native JS) and parse the response
  4. 赶上(xhr。并解析响应
  5. Redirect with window.location.href="success.php"
  6. 重定向和window.location.href = " success.php "

#1


5  

I think it should work for you. Using AJAX, as I do

我想它应该适合你。使用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


2  

You should probably use an AJAX call. Here's a solution using jQuery:

您可能应该使用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>

In order to redirect the user, you can use: window.location.href = " ... your_url ...";

要重定向用户,可以使用:windows .location。href = "……your_url…”;

Here's an explanation on how to use jQuery AJAX and multi-part data:

下面是如何使用jQuery AJAX和多部分数据的说明:

Sending multipart/formdata with jQuery.ajax

发送多部分/ formdata jQuery.ajax

#3


1  

try json_decode.

json_decode试试。

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

by passing 2nd parameter to true you will get response in array instead of object.

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

the array will be then populated as follow:

数组将被填充如下:

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

#4


1  

Your JSON response would be a kind of associative array in php. Encode your array data into JSON using "json_encode" and return values as you want .

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

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

NOTE: If you are using ajax to call php file then do not use any php echo/print in that file and not even HTML. ECHO only "json_encode();" Nothing else.

注意:如果使用ajax调用php文件,那么不要在该文件中使用任何php回显/打印,甚至不要使用HTML。回声只有“json_encode();”什么都没有。

#5


1  

To sum it up:

总结一下:

  1. Upload your data to server using AJAX with native JS (>=IE10) or jQuery
  2. 使用本地JS (>=IE10)或jQuery将数据上载到服务器
  3. Catch (xhr.responseText in native JS) and parse the response
  4. 赶上(xhr。并解析响应
  5. Redirect with window.location.href="success.php"
  6. 重定向和window.location.href = " success.php "