简体   繁体   English

将Blob变量从php发送到javascript

[英]Send blob variable from php to javascript

I have a php file that gets an audio blob from a sql database. 我有一个从sql数据库获取音频blob的php文件。 I need to send that blob to an html page with JavaScript. 我需要将该blob发送到具有JavaScript的html页面。

Below is my PHP code where I send the blob variable $ubr. 下面是我的PHP代码,我在其中发送了blob变量$ ubr。

echo json_encode(array('first'=>$ubr));

Below is my JavaScript where I try and receive the blob. 以下是我尝试接收Blob的JavaScript。

var url = "testThis.php"

var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
//ajax.send(null);
ajax.onreadystatechange = function () {

    if (ajax.readyState == 4 && (ajax.status == 200)) {
        var Data = JSON.parse(ajax.responseText);               
        var b64Data = Data.first;
    }
}

I think it's because I'm treating it like a string but Blobs are binary data. 我认为这是因为我将其视为字符串,但是Blob是二进制数据。 Except I'm not sure what else to do. 除非我不知道该怎么办。

I need to keep the php data as an array. 我需要将php数据保留为数组。 I will need to send a blob and a string value at the same time. 我将需要同时发送一个Blob和一个字符串值。

For AjaxXMLHttpRequest, Server Response can be 对于AjaxXMLHttpRequest,服务器响应可以是

  1. responseText - when you return html or any string as your response. responseText-当您返回html或任何字符串作为响应时。
  2. responseXML - when you return XML as your response. responseXML-当您返回XML作为响应时。
  3. response - when you return response as an Array-buffer, Blob, Document, JavaScript object (for "json"), or string. 响应-当您以数组缓冲区,Blob,文档,JavaScript对象(用于“ json”)或字符串形式返回响应时。 This is null if the request is not complete or was not successful. 如果请求未完成或未成功,则为null。

If you are returning HTML as response ex.PHP code : 如果您返回HTML作为响应,例如PHP代码:

    $data['blob']="blob_value";

   return "<div id='blob'>".$data['blob']."</div><div id='string'>".$data['string']."</div>"; // returning HTML as response .

Then you may use responseText 然后您可以使用responseText

 ajax.onreadystatechange = function () {

             if (ajax.readyState == 4 && (ajax.status == 200)) {

               document.getElementById("target").innerHTML =(ajax.responseText);               

 }

} }

In your case for returning array 在你的情况下返回数组

PHP code can be : PHP代码可以是:

  $data['blob']="blob_value";
  $data['name']="name_value";
  // returning json data ==> {"blob": "blob_value","name": "name_value"}
  return json_encode($data);  

within JavaScript : 在JavaScript中:

   ajax.onreadystatechange = function () {

      if (ajax.readyState == 4 && (ajax.status == 200)) {
         var data= ajax.response;
         var arr= JSON.parse(data);
     alert(arr.blob);                        

       }
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM