将php生成的结果传递回javascript

时间:2017-12-03 10:16:45

标签: javascript php html

我想将PHP生成的结果传递给javascript。因为php_script_response在我成功上传图像后给了我成功的结果[{"结果":" 2gGtqA"}]。我想要找回" 2gGtqA"并将名称存储到我的数据库中,而不是整个" {"结果":" 2gGtqA"}"。

当调用upload.php时,它会生成一个样本" [{"导致":" 78GAVe"}]"

addfacilities.php



<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");

error_reporting(E_ERROR);

include("global.php");

try{
	$conn = new mysqli(server, dbuser, dbpw, db);
	$facilities_ID = $_GET["facilities_ID"];
	$facilities_Img = $_GET["facilities_Img"];

	
	$query = "INSERT Facilities set facilities_ID = '" . $facilities_ID . "'
	, facilities_Img = '" . $facilities_Img . "'";



	$result = $conn->query($query);

	if (!$result){
		$json_out = "[" . json_encode(array("result"=>0)) . "]";		
	}
	else {
		$json_out = "[" . json_encode(array("result"=>1)) . "]";		
	}

	echo $json_out;

	$conn->close();
}
catch(Exception $e) {
	$json_out =  "[".json_encode(array("result"=>0))."]";
	echo $json_out;
}
?>
&#13;
&#13;
&#13;

upload.php的

&#13;
&#13;
<?php
try{
    if (0 < $_FILES['file']['error']) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    } else {

        $filename = tempnam('images', '');
        $new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
        unlink($filename);

        move_uploaded_file($_FILES['file']['tmp_name'], $new_image_name);

        echo "[" . json_encode(array("result"=>$new_image_name)) . "]";
    }
}
catch(Exception $e) {
    $json_out =  "[".json_encode(array("result"=>0))."]";
    echo $json_out;
}
?>
&#13;
&#13;
&#13;

的index.html

<!DOCTYPE html>

<html>
<head>
      <link rel="stylesheet" href="styles.css">
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div class="nav">
    <div class="span10 offset1">
      <form action="#" method="post" name="form_name" id="createform" class="form_class" >

        <div class="control-group ">
           <label class="control-label">Facilities ID</label>
               <div class="controls">
               <input type="text" name="facilities_ID" id="facilities_ID" placeholder="Facilities name">
               </div>
        </div>

        <div class="control-group">
          <label class="control-label">Facilities Image</label>
          <div class="controls">
             <img id="imgNewUser" height="100">
             <input type="file" name="SelectImg" id="SelectImg" value="My Picture" accept="image/*" onchange="onpreviewFile()">
          </div>
        </div>
        <div class="form-actions">
          <button type="button" class="btn btn-success" id="upload-button" onclick="createfacilities()">Update</button>
        </div>
      </form>
    </div>
      <script>
        function onpreviewFile() {
            var preview = document.querySelector('img'); //selects the query named img
            var file    = document.querySelector('input[type=file]').files[0]; //sames as here
            var reader  = new FileReader();

            reader.onloadend = function () {
                preview.src = reader.result;
            }

            if (file) {
                reader.readAsDataURL(file); //reads the data as a URL
                //uploadFile(); // testing
            } else {
                preview.src = "";
            }
        }

        onpreviewFile();

       function uploadFile() {
            var file_data = $('#SelectImg').prop('files')[0];   
            var form_data = new FormData();                  
            form_data.append('file', file_data); // The name here ('file') needs to match what PHP is expecting


            $.ajax({
                url: 'upload.php', // point to server-side PHP script 
                dataType: 'text',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function(php_script_response){
                    alert("success" + php_script_response); // display response from the PHP script, if any
                    _imageresult(php_script_response);
                }
             });
            }

            function _imageresult(php_script_response){
            if (php_script_response !== ""){
               alert("yes image1" + php_script_response.new_image_name);
             } else {
                 alert("no upload");
             }
        }

        function createfacilities() {
            var image = document.getElementById("SelectImg").files[0].name;
            document.getElementById("createform").submit(); //form submission
           document.getElementById("createform").submit(); //form submission
            alert("facilities_ID : " + facilities_ID 
             + "\n\n Form Submitted Successfully.");


            var facilities_ID  = $("#facilities_ID").val();
            //var image1= response; // i would want to get the php_script_response                //alert ("image1 >>>" + image1);

            var url = "http://mp08.mybitmp.org/adelinetest/addfacilities.php";


            var JSONObject = {
                "facilities_ID": facilities_ID,
               //"facilities_Img" : image,
            };

            $.ajax({
                url: url,
                type: 'GET',
                data: JSONObject,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (arr) {
                   uploadFile();
                   _addDescriptionResult(arr);

                },
                error: function () {
                    alert("not okay");
                }
            });
        }

        function _addDescriptionResult(arr) {
            document.getElementById("facilities_ID").innerHTML = localStorage.getItem("facilities_ID");
            if (arr[0].result === 1) {
                alert("okay");
            } else {
                alert("not okay 1");
            }
        }
      </script>
    </div>
  </body>
</html>

0 个答案:

没有答案