将数据从Jquery传递给php超级全局无法正常工作

时间:2018-04-08 08:46:19

标签: php jquery ajax request

我正在尝试使用Jquery将数据从我的js文件传递到php。但是,当我通过浏览器发送请求时,我得到值null。我的php类$ imageurl没有设置,也不是我的超级全局$ _POST。我不知道为什么会这样,因为如果我通过postman设置fullimgurl,我的php请求完全正常。我试图将其发送回解码并编码。它似乎都没有用,这很奇怪,因为它通过邮递员工作。

这是我的Jquery代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
</head>
<body>
<form enctype="multipart/form-data">
<input type="file" accept="image/*" onchange="loadFile(event)" >
<button name="submit" id="submit"></button>
</form>


<img src="" id="output"/>

<div id="textOutput"></div>

<script>
var imgfullurl;

$("#submit").on('click', function(e) {
    e.preventDefault();
    $.ajax({
        url: 'test1.php',
        type: 'POST',
        data: { imgfullurl: imgfullurl },
        dataType: "json",
        contentType : "application/json",
        success: function (data) {
            $('#textOutput').html(data);
            console.log(data);
        },
        error: function (error) {
            alert(error);
        }
    })
})


var loadFile = function(event) {
    var reader = new FileReader();
    reader.onload = function(){
        var output = document.getElementById('output');
        output.src = reader.result;
        imgfullurl = reader.result;
        console.log('imageurl');
        console.log(imgfullurl);
    };
    reader.readAsDataURL(event.target.files[0]);

};


</script>
</body>
</html>

这是我的php文件:

if (isset($_POST['imgfullurl'])){
$imageurl = $_POST['imgfullurl'];
}

echo json_encode($imageurl);

1 个答案:

答案 0 :(得分:1)

尝试使用FormData

例如:

$( "#myForm" ).submit(function( event ) {
  event.preventDefault();

  url = $( "#myForm" ).attr( "action" );
  var formData = new FormData($(this)[0]);

  formData.append("yourkey", "yourvalue");

  $.ajax({
    url: url,
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    dataType: "json",
    contentType: false,
    processData: false,
    success: function (data) {
            if (data=='SUCCESS'){
            alert("Hi");
            //location.reload();

        }
            else

            alert("Something is Wrong !!"+data)
         }

  });