使用ajax调用触发外部函数

时间:2015-03-18 11:52:11

标签: javascript php jquery ajax curl

我试图让函数工作(触发器),例如canvas2image,或者可以通过来自移动设备的jquery ajax调用来实现任何功能。因为我没有使用浏览器,所以我创建了一个用canvas2image调用页面的cURL页面。

具有canvas2image功能的页面向一个页面发送ajax请求,该页面将图像创建为.png并将其保存在服务器上

所以我创建了3页1,其中cURL 1使用canvas2image,1创建并保存图像。

在吸引cURL

的ajax函数下面
function mediafunction(){

$.ajax({
url: 'http://www.server.com/curl.php',
cache: false,
success: function(response) {
    // do something
},
error: function(xhr, error) {
    try {
        console.debug(xhr); 
        console.debug(error);
    } catch (err) {
        alert(err);
    }
   }
});
}

cURL代码:

$url="http://www.server.com/canvastoimage.php?questid=1";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR     1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

canvas2image页面:

var targetDiv = $("#widget");
html2canvas(targetDiv, {
onrendered: function(canvas) {
  var canvasData = canvas.toDataURL("image/png"),
xhr = new XMLHttpRequest();

$.ajax({
url: 'saveimg.php', 
                  type: "POST",
                  async: false,
                  //contentType: 'application/json; charset=utf-8',
                  dataType: "text",
                  data: { "base64data" : canvasData

                   },
                   beforeSend: function () {

  },
  complete: function (response) {

  },
success: function (result) {

result;

                  },
                  error: function (request,error) {
                  //alert(error);
                  }
                  });



 }
 });

保存图片页面:

if ( isset($_POST["base64data"]) && !empty($_POST["base64data"]) ) {    

// get the dataURL
$dataURL = $_POST["base64data"];  

// the dataURL has a prefix (mimetype+datatype) 
// that we don't want, so strip that prefix off
$parts = explode(',', $dataURL);  
$data = $parts[1];  

// Decode base64 data, resulting in an image
$data = base64_decode($data);  

// create a temporary unique file name
$file = 'mediasave/' . uniqid() . '.png';

// write the file to the upload directory
$success = file_put_contents($file, $data);

// return the temp file name (success)
// or return an error message just to frustrate the user (kidding!)
echo $output =    $success ? $file : 'Unable to save this image.';
}

这只有在我使用浏览器访问cURL页面时才有效。 我希望你理解我的错误解释,我不知道如何形容它。

1 个答案:

答案 0 :(得分:0)

cUrl是服务器端命令。它只会读取结果,即你的情况下的html / js代码,但不会执行它。 要解决您的问题(您想要抓取并保存图像),请使用gd库。