ajax json将图像和其他数据发送到远程服务器

时间:2014-07-18 17:46:08

标签: javascript php ajax json

我遇到了一个我无法解决的问题(如果您阅读本文,可能也是如此)。 我想通过AJAX将JSON数据发送到远程服务器。此数据包含图像和字符串:

{
    "question": "Your SquareOff Question", 
    "photo" : "Your photo" // optional
} 

我需要将此JSON发送到" www.so-staging.herokuapp.com/api/v1/squareoffs?auth_token = qSJPySVk5yMsaAVE6mSu"在哪里" qSJPySVk5yMsaAVE6mSu"是我以前要求它的一个标记,并存储在$ _SESSION中,在php端。

所以我需要将此信息发送到我的php页面,然后再发送到远程服务器。这是我的问题。我可以在我的php页面中接收图像,但不能将其重新发送到远程服务器。

我告诉你我的代码。

在Html方面,没什么特别的:

在javascript页面上: 我不知道并在同一时间发送图像和字符串。 (如果你有一个提示,那将是愉快的,但这不是我的鬃毛问题)。

function upload_photo(){
    var photo = document.getElementById('photo');

    /* Create a FormData instance */
    var formData = new FormData();

    /* Add the file */ 
    formData.append('photo', photo.files[0]);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'create_square.php');
    xhr.send(formData);

    /* Check the response status */
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4 && client.status == 200){
            create_square_xhr(); 
        }
    }
}


function create_square_xhr(){

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'create_square.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() {
       if (xhr.readyState == 4 && client.status == 200){
           // response is a iframe who display my question and my image if I have 
           // send one. I display it.
       }
    };

    xhr.send('question=' + document.getElementById('question').value;
}

upload_photo();

在我的php页面(create_square.php)上:

if(isset($_SESSION['token']) && isset($_POST['question']) && isset($_FILES['photo'])){

    $url = 'https://so-staging.herokuapp.com/api/v1/squareoffs?auth_token=' . $token;
    $data = array('question' => $_POST['question'], 'photo' => $_FILES['photo']);
    $data = json_encode($data);

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n",
            'method'  => 'POST',
            'content' => $data
        )
    );

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    echo &result;

}

如果我发送了一个问题,那么回复是一个iframe,我会调出我的问题和我的照片。 但是当我执行此代码时,没有显示图像。 我认为这个问题出现在php页面上,因为我收到了$ _FILES ['照片']。

如果您有任何建议,我将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

我建议通过检查来添加错误检查:$ _FILES [" photo"] ["错误"],这可能会告诉您照片上传是否存在问题

您还必须记住,在使用PHP上传照片时,使用随机生成的名称上传照片时,您通常需要先移动到最终位置,然后才能使用它。

这通常是您在上传照片后访问照片所需要做的事情。

if (file_exists("upload/" . $_FILES["photo"]["name"])) {
  echo $_FILES["photo"]["name"] . " already exists. ";
} else {
  move_uploaded_file($_FILES["photo"]["tmp_name"],
  "upload/" . $_FILES["photo"]["name"]);
  echo "Stored in: " . "upload/" . $_FILES["photo"]["name"];
}